XSD <any>元素

2019-10-16 23:17:59

<any>元素用於擴充套件XSD功能。 它用於通過未在架構中定義的元素擴充套件在一個XSD中定義的complexType元素。

看看下面一個例子 - 檔案person.xsd 中定義了person complexType元素。 address.xsd 中定義了address complexType元素。

檔案: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>

檔案:address.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 = "address">
      <xs:complexType>
         <xs:sequence>
            <xs:element name = "houseNumber" type = "xs:string"/>
            <xs:element name = "street" type = "xs:string"/>
            <xs:element name = "state" type = "xs:string"/>    
            <xs:element name = "zipcode" type = "xs:integer"/>         
         </xs:sequence>
      </xs:complexType>
   </xs:element>

</xs:schema>

如果要在XML中定義具有地址的人員,則以下XML文件格式宣告將無效(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 address.xsd">  

   <person>
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</lastname>

      <address>
         <houseNumber>101</firstname>
         <street>Sector-1,Patiala</lastname>
         <state>Punjab</lastname>
         <zipcode>301202<zipcode>
      </address>

   </person>

</class>

使用

要驗證上面的文件:person.xml,請將<xs:any>新增到person.xsd 中的person元素。如下檔案: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:any minOccurs = "0"/>         
         </xs:sequence>
      </xs:complexType>
   </xs:element>

</xs:schema>

現在,person.xml 將使用檔案:person.xsdaddress.xsd 的定義進行驗證。