我正在尝试实现一个非常简单的XML模式约束。
应该只允许类型元素上的idref属性具有与至少一个元素的id属性匹配的值。
如果这对您没有任何意义,那么请看下面的示例XML文档,我认为它实际上比我试图用语言解释它更好。
那么,问题是:为什么xmllint允许下面的模式/xml组合通过(它说文档是有效的)?如何修复它以实现所需的约束?
模式:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="test" xmlns="test" elementFormDefault="qualified">
<xs:element name="foo">
<xs:complexType>
<xs:sequence>
<xs:element name="bar" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" use="required" type="xs:string" />
</xs:complexType>
</xs:element>
<xs:element name="batz" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="idref" use="required" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:key name="ID">
<xs:selector xpath="./bar" />
<xs:field xpath="@id" />
</xs:key>
<xs:keyref name="IDREF" refer="ID">
<xs:selector xpath="./batz" />
<xs:field xpath="@idref" />
</xs:keyref>
</xs:element>
</xs:schema>该文件:
<?xml version="1.0"?>
<foo xmlns="test">
<bar id="1" />
<bar id="2" />
<batz idref="1" /> <!-- this should succeed because <bar id="1"> exists -->
<batz idref="3" /> <!-- this should FAIL -->
</foo>发布于 2010-01-06 18:21:08
如图所示,您的XML文档不包括schemaLocation。当XML文档不引用模式或DTD时,它可能仅仅是格式良好的XML就可以通过验证。(这种情况曾经发生在一位同事身上,他使用的是不同的验证器。我认为这是一个错误,验证器至少没有给出它缺少模式或DTD的警告。但我离题了。)
总之,应该是这样的:
<?xml version="1.0"?>
<foo
xmlns="test" <!-- This is bad form, by the way... -->
xsi:schemaLocation="test /path/to/schema/document"
<bar id="1" />
<bar id="2" />
<batz idref="1" /> <!-- this should succeed because <bar id="1"> exists -->
<batz idref="3" /> <!-- this should FAIL -->
</foo>发布于 2010-01-06 19:04:31
即使分配了模式位置,这也不会在所有解析器中工作。
<?xml version="1.0"?>
<foo xmlns="test"
xsi:schemaLocation="test test.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<bar id="1" />
<bar id="2" />
<batz idref="1" /> <!-- this should succeed because <bar id="1"> exists -->
<batz idref="3" /> <!-- this should FAIL -->
</foo>这也将验证,因为键不是引用目标命名空间。
需要在XSD中进行的更改如下
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="test"
xmlns:t="test"
xmlns="test" elementFormDefault="qualified">和
<xs:key name="ID">
<xs:selector xpath="./t:bar" />
<xs:field xpath="@id" />
</xs:key>
<xs:keyref name="IDREF" refer="ID">
<xs:selector xpath="./t:batz" />
<xs:field xpath="@idref" />
</xs:keyref>有关此行为的讨论,请参阅#1545101
https://stackoverflow.com/questions/2015059
复制相似问题