我有兴趣在我的 Xsd 中定义一个关键约束。我的理解是 usingxs:key
应该将使用的值限制为引用的值列表的成员。
假设我们使用的是样本 Xsd,
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="namespace1"
xmlns:r="namespace1"
elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="A" type="r:A" maxOccurs="unbounded">
<xs:keyref name="dummy" refer="r:pNumKey">
<xs:selector xpath="part"/>
<xs:field xpath="@ref-number"/>
</xs:keyref>
</xs:element>
<xs:element name="B" type="r:B"/>
</xs:sequence>
</xs:complexType>
<xs:key name="pNumKey">
<xs:selector xpath="r:B/r:part"/>
<xs:field xpath="@key-number"/>
</xs:key>
</xs:element>
<xs:complexType name="A">
<xs:sequence>
<xs:element name="part" maxOccurs="unbounded">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="ref-number" type="xs:integer"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="B">
<xs:sequence>
<xs:element name="part" maxOccurs="unbounded">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="key-number" type="xs:integer"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>
样品 Xml,
<root xmlns="namespace1">
<A>
<!--
if the ref-number is not equal to one of the key-number,
the validation will give error
-->
<part ref-number="1"/>
</A>
<A>
<!--
if the ref-number is not equal to one of the key-number,
the validation will give error
-->
<part ref-number="2"/>
</A>
<B>
<part key-number="1"/>
<part key-number="2"/>
<part key-number="3"/>
</B>
</root>
并且,比如说,一些简单的验证
[TestMethod]
public void Test_Schema()
{
string schemaFileName = @"sampleSchema.xsd";
string xmlFileName = @"sampleXml.xml";
XmlReaderSettings settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema,
ValidationFlags =
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings,
};
settings.Schemas.Add (schema);
settings.ValidationEventHandler +=
(o, e) => { throw new Exception("CRASH"); };
XmlSchema schema =
XmlSchema.Read (
File.OpenText (schemaFileName),
(o, e) => { throw new Exception ("BOOM"); });
XmlReader reader = XmlReader.Create (xmlFileName, settings);
while (reader.Read ()) { }
}
怎么样,当我使用错误的值时,验证仍然成功A/part[@ref-number]
?
<root xmlns="namespace1">
<A>
<!-- doesn't go CRASH BOOM bang! why not? :( -->
<part ref-number="5"/>
</A>
<B>
<part key-number="1"/>
<part key-number="2"/>
<part key-number="3"/>
</B>
</root>
以上 Xsd、Xml 或验证中的任何一项或全部是否不正确?还是我误解了 的预期目的xs:key
?