2008-10-08 108 views
2

我試圖驗證XML如下:使用模式如何使用Schema驗證基於屬性值的元素?

<root> 
    <element attribute="foo"> 
     <bar/> 
    </element> 
    <element attribute="hello"> 
     <world/> 
    </element> 
</root> 

這可怎麼驗證?

注:

元件只能包含酒吧屬性= 「foo」 的

元素只能包含世界屬性= 「你好」

回答

6

不能在XML模式1.0做到這一點。在XML Schema 1.1中,您將能夠使用<xs:assert> element來做到這一點,但我猜你想要現在可以使用的東西。

您可以使用Schematron作爲驗證的第二層,它允許您測試關於XML文檔的任意XPath斷言。有一篇關於embedding Schematron in XSD的相當老的文章,您可能會發現有幫助。

你會做這樣的事情:

<rule context="element"> 
    <report test="@attribute = 'foo' and *[not(self::bar)]"> 
    This element's attribute is 'foo' but it holds an element that isn't a bar. 
    </report> 
    <report test="@attribute = 'hello' and *[not(self::world)]"> 
    This element's attribute is 'hello' but it holds an element that isn't a world. 
    </report> 
</rule> 

或課程,你可以切換到RELAX NG,這確實該在其睡眠:

<element name="element"> 
    <choice> 
    <group> 
     <attribute name="attribute"><value>foo</value></attribute> 
     <element name="bar"><empty /></element> 
    </group> 
    <group> 
     <attribute name="attribute"><value>hello</value></attribute> 
     <element name="world"><empty /></element> 
    </group> 
    </choice> 
</element>