Allow XML element in any order with any number of appearance via XSD?

a 夏天 提交于 2021-02-05 09:13:09

问题


I have trouble to write XSD with these constraints: Name element is required; Value element could appear 0 or multiple times; Category element is optional. I now have XSD like this:

<xs:element name="Detail" maxOccurs="unbounded" minOccurs="0"> <!-- 0 or more Details -->
  <xs:complexType>
    <xs:sequence>
      <xs:element type="xs:string" name="Name"/> <!-- Name element is required -->
      <xs:element type="xs:string" name="Value" maxOccurs="unbounded" minOccurs="0"/> <!-- 0 or more occurences of Value element -->
      <xs:element type="xs:string" name="Category" minOccurs="0" maxOccurs="1"/> <!-- optional (0 or 1) Category element -->
    </xs:sequence>
  </xs:complexType>
</xs:element>

The problem is that input XML may not follow the order in the schema. And xs:choice and xs:all have appearance constraint that are not good enough for me.

Can anyone help me to solve this problem that allow XML element in any order with any number of times appearance?

Attach a sample input XML:

<Detail>
    <Category />
    <Name> Thanks </Name>
    <Value> 1 </Value>
    <Value> 2 </Value>
</Detail>

回答1:


XSD 1.0

Not possible. Either impose an order, or relax occurrence constraints.

XSD 1.1

Possible, because in XSD 1.1, children of xs:all may now have @maxOccurs="unbounded":

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           elementFormDefault="qualified"
  vc:minVersion="1.1">
  <xs:element name="Detail"> 
    <xs:complexType>
      <xs:all>
        <xs:element type="xs:string" name="Name"/>
        <xs:element type="xs:string" name="Value" 
                    minOccurs="0" maxOccurs="unbounded" />
        <xs:element type="xs:string" name="Category" 
                    minOccurs="0" maxOccurs="1"/>
      </xs:all>
    </xs:complexType>
  </xs:element>
</xs:schema>


来源:https://stackoverflow.com/questions/39907723/allow-xml-element-in-any-order-with-any-number-of-appearance-via-xsd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!