默認情況下,XSD中的元素必須存在。如果未指定,子元素的minOccurs
屬性設置爲1。
也就是說,你必須明確地通過設置minOccurs="0"
使元素可選。
實施例模式
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="parentTag">
<xs:complexType>
<xs:sequence>
<xs:element name="childTag1" minOccurs="0"/> <!-- This element is optional -->
<xs:element name="childTag2"/> <!-- This element is required -->
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
測試有效的XML(使用xmllint)
<?xml version="1.0"?>
<parentTag>
<childTag1>
<!-- ... stuff -->
</childTag1>
<childTag2>
<!-- ... stuff -->
</childTag2>
</parentTag>
testfile.xml validates
測試無效的XML
<?xml version="1.0"?>
<parentTag>
<childTag1>
<!-- ... stuff -->
</childTag1>
</parentTag>
testfile.xml:2: element parentTag: Schemas validity error : Element 'parentTag': Missing child element(s). Expected is (childTag2).
testfile.xml fails to validate
+1,儘管'minOccurs =「1」'是默認值,所以不需要明確指定它。 – skaffman
@skaffman好點。我會將其添加到答案中。 – 2012-05-16 22:40:24
謝謝,這非常有幫助:) –