<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://www.tw511.com"
xmlns = "https://www.tw511.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://www.tw511.com"
xmlns = "https://www.tw511.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 = "https://www.tw511.com"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "https://www.tw511.com person.xsd
https://www.tw511.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 = "https://www.tw511.com"
xmlns = "https://www.tw511.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 給出的定義進行驗證。