为此,您可以使用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>