XSD <anyAttribute>元素

2019-10-16 23:18:00

<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.xsdattributes.xsd 給出的定義進行驗證。