这取决于。在 XSD 中,您可以从结构的角度定义 xml。结构和内容之间的关系在 XSD 1.0 中更难表达。
您可以使用 xsi:type 属性使用类型替换。XSD 可能看起来像
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<!-- Let be Animals root element -->
<xs:element name="Animals" type="animals" />
<!-- type for Animals elemes -->
<xs:complexType name="animals">
<xs:sequence>
<xs:element name="Animal" maxOccurs="unbounded" type="animal"/>
</xs:sequence>
</xs:complexType>
<!-- Define an abstract type for animal (abstract = there shouldn't occure element of this type only of its childs). It has no attributes. -->
<xs:complexType name="animal" abstract="true">
<xs:simpleContent>
<xs:extension base="xs:string"/>
</xs:simpleContent>
</xs:complexType>
<!-- Define a type for cat... -->
<xs:complexType name="catType">
<xs:simpleContent>
<!-- ... it extends abstract animal type ... -->
<xs:extension base="animal">
<!-- ... and add some attributes with fixed values -->
<xs:attribute name="name" fixed="cat" />
<xs:attribute name="nbOfLegs" fixed="4" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<!-- similar definition like catType -->
<xs:complexType name="kangarooType">
<xs:simpleContent>
<xs:extension base="animal">
<xs:attribute name="name" fixed="kangaroo" />
<xs:attribute name="nbOfLegs" fixed="2" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:schema>
以下 XML 应验证
<?xml version="1.0" encoding="UTF-8"?>
<Animals xsi:noNamespaceSchemaLocation="animals.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- xsi:type is saying what type is actually used -->
<Animal xsi:type="catType" name="cat" nbOfLegs="4" />
<Animal xsi:type="kangarooType" name="kangaroo" nbOfLegs="2" />
</Animals>
跟随不
<?xml version="1.0" encoding="UTF-8"?>
<Animals xsi:noNamespaceSchemaLocation="animals.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Animal xsi:type="catType" name="cat" nbOfLegs="2" />
</Animals>
(出现错误,例如属性 'nbOfLegs' 的值 '2' 不等于固定默认值 '4')。