2

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>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
amanda
  • 23
  • 4

2 Answers2

3

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.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • But the number of labtest tags are unknow may be increaing so thats not the solution @micheal kay – amanda Feb 13 '17 at 18:15
  • @Micheal how can i skip checking on labtest using skip ? – amanda Feb 13 '17 at 18:20
  • It's precisely because the number of labtest tags is unknown that you are better off using a different structure. XSD is designed to validate documents using a fixed finite vocabulary of tag names. – Michael Kay Feb 13 '17 at 21:41
2

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.
kjhughes
  • 106,133
  • 27
  • 181
  • 240