Search code examples
xmlxsdxsi

Is it possible to define an XML attribute for an element by an additional XSD?


Let's say I have an XML something like this:

<root xmlns="default" xmlns:add="additional">
    <element foo="fromDefault" />
    <add:element foo="fromDefault" add:bar="fromAdditional" />
</root>

What I would like to do is to merge the two element definitions to avoid duplications, something like this:

<root xmlns="default" xmlns:add="additional">
    <element foo="fromDefault" add:bar="fromAdditional" />
</root>

But I'm not even sure if this is possible.

I have the feeling it might be doable because we use some similar notations for the root elements like:

<root xmlns:xsi="..."
         xsi:schemaLocation="...">

Unfortunately I wasn't able to find any docs/references/tutorials/anything about this issue, could someone help me clarify if what I would like to do is possible (or not) and share some links with me?

Thanks in advance!


Solution

  • I think that you are looking for something like this:

    additional.xsd

    <xs:schema 
      targetNamespace="additional"
      elementFormDefault="qualified"
      xmlns="additional"
      xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
      xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
      <xs:attribute name="bar" type="xs:string"/>
    
    </xs:schema>
    

    default.xsd

    <xs:schema 
      targetNamespace="default"
      elementFormDefault="qualified"
      xmlns="default"
      xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:add="additional">
    
      <xs:import namespace="additional" schemaLocation="additional.xsd"/>
    
      <xs:element name="root">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="element" minOccurs="1" maxOccurs="1">
              <xs:complexType>
                <xs:attribute name="foo" type="xs:string"/>
                <xs:attribute ref="add:bar"/>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    
    </xs:schema>
    

    The first schema defines only the 'additional' stuff (in the example just an attribute) and the second schema imports it and defines everything else, referencing the additional stuff where needed.