3

我在制作复杂元素时遇到了问题,它允许可选元素和强制元素。对于下面的 xml,说 h2 是强制性的,而 h1 是可选的,顺序无关紧要。

情况1:

<root>
<h1/>
<h2/>
</root>

案例二:

<root>
<h2/>
</root>

案例3:

<root>
<h2/>
<h1/>
</root>

XSD:

<xs:element name="root">
    <xs:complexType>
           <xs:sequence minOccurs="1" maxOccurs="unbounded">
               <xs:element name="h1" minOccurs="0"></xs:element>
                <xs:element name="h2" minOccurs="1" />
           </xs:sequence>
     </xs:complexType>
</xs:element>

上述第三种情况在此 xsd 中失败,但这种情况是有效的。我需要一个对上述所有情况都有效的 xsd。

4

1 回答 1

0

Knowing that what you want is:

to make h2 occur atmost 1, while h1 can occur as many times as possible

You could use this XSD in which you are defining that a XML would be valid if its content is something like (RegExpr) <root><h1/>*<h2/><h1/>*</root>.

XSD:

<?xml version="1.0" encoding="iso-8859-1"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="root">
    <xsd:complexType>
      <xsd:sequence minOccurs="1" maxOccurs="1">
        <xsd:element name="h1" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element name="h2" minOccurs="1" maxOccurs="1"/>
        <xsd:element name="h1" minOccurs="0" maxOccurs="unbounded"/>        
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>


Valid XML examples:
1)

<root>
  <h1/>
  <h1/>
  <h2/>
  <h1/>
</root>

2)

<root>
  <h1/>
  <h2/>
</root>


Invalid XML example:
Two <h2/> Elements.

<root>
  <h2/>
  <h1/>
  <h2/>
</root>

No <h2/> Element.

<root>
  <h1/>
  <h1/>
</root>
于 2012-06-12T19:52:37.540 回答