xml schema construct for elements to occur any number of times in any order

放肆的年华 提交于 2020-01-02 16:18:20

问题


i wanna write an xml schema that can accept some elements that can occur any number of times in any order. like following examples. it should satisfy all similar combination. lease help me and thanks in advance.

Example 1

<root>
    <node1> one   </node1>
    <node1> two   </node1>
    <node2> three </node2>
    <node1> four  </node1>
    <node2> five  </node2>
    <node2> six   </node2>
</root>

Example 2

<root>    
    <node1> one   </node1>
    <node2> two   </node2>
    <node1> three </node1>
    <node2> four  </node2>
    <node2> five  </node2>
    <node1> six   </node1>
    <node1> seven </node1>
</root>

回答1:


Something like this should work:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="root" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="node1" nillable="true">
          <xs:complexType>
            <xs:simpleContent>
              <xs:extension base="xs:string">
              </xs:extension>
            </xs:simpleContent>
          </xs:complexType>
        </xs:element>
        <xs:element name="node2" nillable="true">
          <xs:complexType>
            <xs:simpleContent>
              <xs:extension base="xs:string">
              </xs:extension>
            </xs:simpleContent>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

Basically, the <xs:choice> gives you the option to pick any one of the contained nodes, e.g. any one of <node1> or <node2>. See W3Schools' article for more explanations about the various options.

Since the <xs:choice> has attributes minOccurs="0" and maxOccurs="unbounded", you can repeat that "pick any of the contained nodes" scenario any number of times.

In the end, you can pick any number of nodes, and each time, you can pick either node1 or node2 (or more, if you add more options to the <xs:choice>)




回答2:


marc_s 's answer hits the nail right on the head.

When I was writing schemas, I found this resource to be very useful: http://www.w3schools.com/Schema/schema_elements_ref.asp



来源:https://stackoverflow.com/questions/3377805/xml-schema-construct-for-elements-to-occur-any-number-of-times-in-any-order

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