XML namespaces and attributes

前端 未结 4 662
梦谈多话
梦谈多话 2020-11-27 15:43

I\'m trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Ar

4条回答
  •  佛祖请我去吃肉
    2020-11-27 16:32

    There's something related to this attributes/namespaces subject that took me some time to understand today when I was working on a XSD. I'm going to share this experience with you in case anyone ever happens to have the same issues.

    In the Schema Document I was working on there were a couple of global attributes referenced by some elements. To simplify things here let's assume this XSD I'm talking about was about a Customer.

    Let's call one of these global attributes Id. And the root element using it Customer

    My XSD declaration looked like this :

    
    
    

    My Id attribute declaration looked like this :

    
    

    And my Customer element used the attribute like this :

    
       
          
          
        
    
    

    Now, let's say I wanted to declare a Customer XML document like this :

    
    
      
    
    

    I found out that I can't : when the attribute is globally declared, it's not in the same namespace than the element who references it.

    I figured out that the only solution with the XSD defined like that was to declare the namespace twice: once without a prefix in order to make it the default namespace for elements, and once with a prefix in order to use it with the attributes. So this is how it would have looked like :

    
    
      
    
    

    This is so unpractical that I just decided to get rid of all global attributes and declare them them locally. Wich in the case of the example I gave here would have looked like this:

    
       
           
           
       
    
    

    I found it hard to find some references about what I'm talking about here in the net. I eventually found this post in the Stylus XSD Forum where a guy named Steen Lehmann suggested either to declare the attribute locally or to declare it within an attribute group

    "so that the attribute declaration itself is no longer global"

    This last solution has a "hacky" taste, so I just decided to stick with the first solution and declare all my attributes locally.

提交回复
热议问题