开发者

XML validation against XSD failing when node has multiple children

I need to generate a XSD for a XML file we are gonna use between systems so we can validate if the data we get is valid.

The XML looks like this (but with more fields):

<Request>
<Request_ID>1000012295</Request_ID>
<Extra_Info>
  <Item>
    <Item_Number>0000000001</Item_Number>
    <ItemDescription>test- 2</ItemDescription>    
  </Item>
  <Item>
    <Item_Number>0000000002</Item_Number>
    <ItemDescription>test - 2</ItemDescription>
  </Item>
</Extra_Info>
</Request>

and my XSD is the following:

<?xml version="1.0" encoding="utf-16"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="Request">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Request_ID" type="xsd:int" />
        <xsd:element name="Extra_Info">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="Item">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="Item_Number" type="xsd:int" />
                    <xsd:element name="ItemDescription" type="xsd:string" />
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

This schema works when I only have one Item node, but开发者_运维技巧 as soon as I have more than one I get the following error:

The element 'Extra_Info' has invalid child element 'Item'.

why is it not working if it is specified as a sequence?

Thanks!

PS: I used This Online Validator for quick validation, but I also get the same error with XMLReader


By default min and max occurs for an element are set to 1 even when defined inside a sequence

your Extra_Info element definition should be as follows:

<xsd:element name="Extra_Info">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="Item" maxOccurs="unbounded">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="Item_Number" type="xsd:int" />
            <xsd:element name="ItemDescription" type="xsd:string" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>

Note: the unbounded attribute which states you can have 1 or more of these elements.

To have any number of items you can add minOccurs='0' to the item element so it looks like this:

<xsd:element name="Item" maxOccurs="unbounded" minOccurs="0">


You must add the attribute maxOccurs="unbounded" to the element Item in your xsd file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜