JBird
JBird

Reputation: 211

How to have different elements with same name but different type in XSD v1.0

I've a codebase that is relatively large that incorporates 2 types of XML:

<tag ref="var_ref" />

or

<tag>value</tag>

However, I want the following to fail to validate because it is in our case ambiguous.

<tag ref="var_ref">value</tag>

I see that alternatives are possible in v1.1, but does anyone have a hack for XSD 1.0?

Upvotes: 1

Views: 248

Answers (1)

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25034

The easiest hack for 1.0 is to give distinct names to these two distinct validation behaviors. (Some authorities would say that this is not a hack but just simpler design. Why give the same name to two things which are so obviously different in structure? Call things what they are: when they are different, call them different things. It makes many things simpler, including XML and XML processing.)

If your target namespace is bound to prefix tns, you might write:

<xsd:element name="tns:TAG" abstract="true"/>
<xsd:element name="tag" type="xsd:string" 
             substitutionGroup="tns:TAG"/>
<xsd:element name="tagref" 
             substitutionGroup="tns:TAG">
  <xsd:sequence/>
  <xsd:attribute name="ref" type="xsd:IDREF"/>
  <!--* or adjust the type to suit ... *-->
</xsd:element>

Then replace all references to tns:tag in your existing content models with references to tns:TAG.

Upvotes: 1

Related Questions