<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 = "http://www.yiibai.com"
xmlns = "http://www.yiibai.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 = "http://www.yiibai.com"
xmlns = "http://www.yiibai.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
元素的age
属性,则以下声明将无效。文件:person.xml -
<?xml version = "1.0"?>
<class xmlns = "http://www.yiibai.com"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.yiibai.com person.xsd
http://www.yiibai.com attributes.xsd">
<person age = "20">
<firstname>Max</firstname>
<lastname>Su</lastname>
<nickname>Maxsu</nickname>
</person>
</class>
使用
要验证上面的person.xml,请将<xs:anyAttribute>
添加到person.xsd 文件中的person
元素中。如下所示 -
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
targetNamespace = "http://www.yiibai.com"
xmlns = "http://www.yiibai.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 给出的定义进行验证。