XSD <anyAttribute> 元素

element <anyAttribute> ให้แก่เราความสามารถในการขยาย XML document ด้วยคุณสมบัติที่ยังไม่ถูกกำหนดโดย schema!

element <anyAttribute>

element <anyAttribute> ให้แก่เราความสามารถในการขยาย XML document ด้วยคุณสมบัติที่ยังไม่ถูกกำหนดโดย schema!

ตัวอย่างดังนี้คือส่วนหนึ่งของ XML schema ที่มีชื่อว่า "family.xsd" มันแสดงให้เห็นถึงการประกาศของ element "person" โดยใช้ element <anyAttribute> เราสามารถเพิ่มคุณสมบัติอื่นๆ ให้กับ element "person" ได้จำนวนที่ไม่จำกัด:

<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
    <xs:anyAttribute/>
  </xs:complexType>
</xs:element>

现在,我们希望通过 "gender" 属性来扩展 "person" 元素。在这种情况下我们就可以这样做,即使这个 schema 的作者从未声明过任何 "gender" 属性。

请看这个 schema 文件,名为 "attribute.xsd":

<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.codew3c.com"
xmlns="http://www.codew3c.com"
elementFormDefault="qualified">
<xs:attribute name="gender">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:pattern value="male|female"/>
    </xs:restriction>
  </xs:simpleType>
</xs:attribute>
</xs:schema>

下面这个 XML(名为 "Myfamily.xml"),使用了来自不同 schema 的成分,"family.xsd" 和 "attribute.xsd":

<?xml version="1.0" encoding="ISO-8859-1"?>
<persons xmlns="http://www.microsoft.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:SchemaLocation="http://www.microsoft.com family.xsd
http://www.codew3c.com attribute.xsd">
<person gender="female">
<firstname>Jane</firstname>
<lastname>Smith</lastname>
</person>
<person gender="male">
<firstname>David</firstname>
<lastname>Smith</lastname>
</person>
</persons>

上面這個 XML 文件是有效的,因為 schema "family.xsd" 允許我們向 "person" 元素添加屬性。

<any> 和 <anyAttribute> 均可用於製作可擴展的文檔!它們使文檔有能力包含未在主 XML schema 中聲明過的附加元素。