amanda
amanda

Reputation: 23

Want to write schema for XML file

I want to write schema which validates my following xml

<labtest>
    <labtest_id1>10190</labtest_id1>
    <labtest_id2> 10200</labtest_id2>
    <labtest_id3> 10220</labtest_id3>
</labtest>

The number of tags <labtest_id> may be increasing or decreasing. I validate like this but it is not working

    <xs:element name="labtest" minOccurs="1" maxOccurs="unbounded">
      <xs:complexType>
        <xs:sequence>
            <xs:element name="labtest_id" minOccurs="1" type="xs:decimal"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>

Upvotes: 2

Views: 35

Answers (2)

kjhughes
kjhughes

Reputation: 111716

Change your XML design as Michael Kay recommends and still support multiple labtest elements as well as multiple labtest_id elements:

This XML,

<?xml version="1.0" encoding="UTF-8"?>
<labtests>
  <labtest>
    <labtest_id>10190</labtest_id>
    <labtest_id>10200</labtest_id>
    <labtest_id>10220</labtest_id>
  </labtest>
  <labtest>
    <labtest_id>12345</labtest_id>
  </labtest>
</labtests>

will validate successfully against this XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="labtests">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="labtest" minOccurs="1" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="labtest_id" minOccurs="1"
                          maxOccurs="unbounded" type="xs:decimal"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Notes:

  • You want labtest to repeat, but there can only be one root element in well-formed XML, so add a labtests wrapper element.
  • You want labtest_id to repeat, so add a maxOccurs="unbounded" to its declaration.

Upvotes: 2

Michael Kay
Michael Kay

Reputation: 163587

If you want to impose the constraint that all the children of labtest must be named labtest_N where N is an integer, that's something you can't do with XSD (except perhaps using XSD 1.1 with assertions).

This is an awful way to use XML, and the best thing to do is first to transform it to something sane using XSLT, for example to:

<labtests>
  <labtest id='1'>10190</labtest>
  <labtest id='2'>10200</labtest>
  <labtest id='3'>10220</labtest>
</labtests>

and then validate the result with XSD.

Upvotes: 3

Related Questions