SteveC
SteveC

Reputation: 16823

How can you define an element by position in XML Schema?

How can you define an element by position in XML Schema?

We're getting various XML data feeds with the data as a series of <row> elements, with the actual values as <value>.

The XML files do have a <metadata> element at the beginning

But how can I say in XSD that the first <value> in each <row> should be, e.g. xsd:dateTime?

... XML snippet !

<metadata>
      <item name="Month" type="xs:date"/>
      <item name="Planned Total" type="xs:double" precision="2"/>
</metadata>
<data>
    <row>
        <value>2019-11-01</value>
        <value>3607</value>
    </row>
    <row>
        <value>2019-12-01</value>
        <value>3091</value>
    </row>

... rest of XML ...

Upvotes: 1

Views: 653

Answers (2)

Michael Kay
Michael Kay

Reputation: 163595

Don't overlook the possibility of doing an XSLT transformation (to a more natural XML structure) followed by XSD validation of the output. That's possible whether you end up using the "more natural" XML for further application processing, or whether it exists only transiently for validation purposes.

Upvotes: 1

kjhughes
kjhughes

Reputation: 111726

To define an element by position in XML Schema, use xsd:sequence and use different element names for different types:

  <xs:element name="row">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="date" type="xs:dateTime"/>
        <xs:element name="total" type="xs:integer"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

Any design that has different types for same-named sibling elements is misguided. Such a constraint cannot be represented in DTD or XSD 1.0. It can be represented via assertions in XSD 1.1, but that would be rather unnatural.

Note also that your presented XML is not well-formed.

See also:

Upvotes: 1

Related Questions