gpt4 book ai didi

xml - XSD key/keyref 新手问题

转载 作者:数据小太阳 更新时间:2023-10-29 01:42:24 25 4
gpt4 key购买 nike

我正在尝试实现一个非常简单的 XML 架构约束。

The idref attribute on elements of type <batz> should only be allowed to have a value that matches the id attribute on at least one element <bar>.

如果这对您没有任何意义,那么请看下面的示例 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>

最佳答案

即使分配了模式位置,这也不会在所有解析器中工作。

<?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>

这也将验证,因为 key 未引用目标命名空间。

需要在 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

关于xml - XSD key/keyref 新手问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2015059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com