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.tw"
   xmlns = "https://tutorialspoint.tw"
   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.tw"
   xmlns = "https://tutorialspoint.tw"
   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.tw"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "https://tutorialspoint.tw person.xsd
   https://tutorialspoint.tw 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.tw"
   xmlns = "https://tutorialspoint.tw"
   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.xsdattributes.xsd 進行驗證。

xsd_complex_types.htm
廣告
© . All rights reserved.