我正在尝试开发一个模式,它将验证我继承的一些现有XML文件。我希望让模式来做尽可能多的验证工作。挑战在于属性和元素依赖于其他属性的值。
真实的数据非常抽象,所以我创建了一些简单的示例。假设我有以下XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<Creature type="human" nationality="British">
<Address>London</Address>
</Creature>
<?xml version="1.0" encoding="UTF-8"?>
<Creature type="animal" species="Tiger">
<Habitat>Jungle</Habitat>
</Creature>如果这个生物的"type“是"human",我将有一个"nationality”属性和一个"Address“子元素。如果生物的“类型”是“动物”,我将有一个“种”属性和一个“栖息地”子元素。在这个例子中,带有“物种”或“栖息地”的“人类”是无效的--带有“国籍”或“地址”的“动物”也是无效的。
如果“生物”不是根元素,我可能会在根元素下面有两个不同的“生物”选项,但当“生物”是根元素时,我不知道如何才能做到这一点。
有没有办法为这些文件创建一个只与有效文档匹配的模式?如果是这样的话,我该怎么做呢?
发布于 2009-10-21 23:17:28
为此,您可以使用xsi:type属性(您必须使用XMLSchema实例名称空间中的xsi:type,而不是您自己的名称空间,否则它将无法工作)。
在模式中,您声明一个声明为抽象的基类型,并为每个子类型创建额外的复杂类型(具有特定于该类型的元素/属性)。
请注意,虽然此解决方案有效,但最好为每种类型使用不同的元素名称( xsi:type有点不合常理,因为它现在是type属性与定义类型的元素名称的组合,而不仅仅是元素名称)。
例如:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Creature" type="CreatureType">
</xs:element>
<xs:complexType name="CreatureType" abstract="true">
<!-- any common validation goes here -->
</xs:complexType>
<xs:complexType name="Human">
<xs:complexContent>
<xs:extension base="CreatureType">
<xs:sequence maxOccurs="1">
<xs:element name="Address"/>
</xs:sequence>
<xs:attribute name="nationality" type="xs:string"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Animal">
<xs:complexContent>
<xs:extension base="CreatureType">
<xs:sequence maxOccurs="1">
<xs:element name="Habitat"/>
</xs:sequence>
<xs:attribute name="species" type="xs:string"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>此模式将验证这两个:
<?xml version="1.0" encoding="UTF-8"?>
<Creature xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="Human"
nationality="British">
<Address>London</Address>
</Creature>
<?xml version="1.0" encoding="UTF-8"?>
<Creature xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="Animal"
species="Tiger">
<Habitat>Jungle</Habitat>
</Creature>但不是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<Creature xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="SomeUnknownThing"
something="something">
<Something>Something</Something>
</Creature>或者这样:
<?xml version="1.0" encoding="UTF-8"?>
<Creature xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="Human"
species="Tiger">
<Habitat>Jungle</Habitat>
</Creature>https://stackoverflow.com/questions/1600265
复制相似问题