Question

How do I create an xsd that can validate either of the following two examples?

<element attribute="attribute-value" />

and

<element attribute="attribute-value">element-value</element>
Was it helpful?

Solution

  <?xml version="1.0" encoding="utf-8"?>
  <xs:schema id="test"
      targetNamespace="http://tempuri.org/test.xsd"
      elementFormDefault="qualified"
      xmlns="http://tempuri.org/test.xsd"
      xmlns:mstns="http://tempuri.org/test.xsd"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
  >
    <xs:complexType name="element_type">
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute name="attribute" type="xs:string" />
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>

    <xs:element name="root">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="element" type="element_type">
          </xs:element>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:schema>

This assumes that the attribute isn't required.

OTHER TIPS

You would use xsd:simpleContent for this. Here is an example.

For completeness, I added some validation parameters as follows:

<xsd:element name="element">
  <xsd:complexType>
    <xsd:simpleContent>
        <xsd:extension base="OptionalString">
            <xsd:attribute name="row" type="xsd:positiveInteger"
                use="required" />
        </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>
</xsd:element>

<xsd:simpleType name="OptionalString">
<xsd:restriction base="xsd:string">
    <xsd:minLength value="0" />         
</xsd:restriction>
</xsd:simpleType>

Would this be different from the solution proposed above?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top