XSD - <anyAttribute>
使用 <xs:anyAttribute> 元素可扩展 XSD 功能。可用于扩展一个 xsd 中定义的 complexType 元素,该元素包括模式中未定义的属性。
考虑一个示例 - person.xsd 已定义 person complexType 元素。attributes.xsd 已定义 age 属性。
person.xsd
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
targetNamespace = "https://tutorialspoint.com"
xmlns = "https://tutorialspoint.com"
elementFormDefault = "qualified">
<xs:element name = "person">
<xs:complexType >
<xs:sequence>
<xs:element name = "firstname" type = "xs:string"/>
<xs:element name = "lastname" type = "xs:string"/>
<xs:element name = "nickname" type = "xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
attributes.xsd
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
targetNamespace = "https://tutorialspoint.com"
xmlns = "https://tutorialspoint.com"
elementFormDefault = "qualified">
<xs:attribute name = "age">
<xs:simpleType>
<xs:restriction base = "xs:integer">
<xs:pattern value = "[0-100]"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:schema>
如果想在 XML 中定义带有年龄的个人,则以下声明将无效。
person.xml
<?xml version = "1.0"?>
<class xmlns = "https://tutorialspoint.com"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "https://tutorialspoint.com person.xsd
https://tutorialspoint.com attributes.xsd">
<person age = "20">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
</person>
</class>
使用 <xs:anyAttribute>
为验证上述 person.xml,请将 <xs:anyAttribute> 添加到 person.xsd 中 person 元素。
person.xsd
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
targetNamespace = "https://tutorialspoint.com"
xmlns = "https://tutorialspoint.com"
elementFormDefault = "qualified">
<xs:element name = "person">
<xs:complexType >
<xs:sequence>
<xs:element name = "firstname" type = "xs:string"/>
<xs:element name = "lastname" type = "xs:string"/>
<xs:element name = "nickname" type = "xs:string"/>
</xs:sequence>
<xs:anyAttribute/>
</xs:complexType>
</xs:element>
</xs:schema>
现在 person.xml 将针对 person.xsd 和 attributes.xsd 进行验证。
xsd_complex_types.htm
广告