2012-05-16 42 views
0

這是一個非常簡單的問題,但我的Google技巧還沒有得到我的答案,所以:XSD - 強制使用子標籤?

XSD是否可以強制將元素存在於更高級別的元素中?我知道你可以允許或禁止「顯式設置爲零」,但這聽起來不是一回事。

例如:

<parentTag> 
    <childTag1> 
     ... stuff 
    </childTag1> 
    <childTag2> <!-- FAIL VALIDATION IF a childTag2 isn't in parentTag!!! --> 
     ... stuff 
    </childTag2> 
</parentTag> 

如果是這樣,什麼是語法?

回答

2

默認情況下,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 
+0

+1,儘管'minOccurs =「1」'是默認值,所以不需要明確指定它。 – skaffman

+0

@skaffman好點。我會將其添加到答案中。 – 2012-05-16 22:40:24

+0

謝謝,這非常有幫助:) –