目录

XSD 的 <anyAttribute> 元素


<anyAttribute> 元素使我们能够使用架构未指定的属性来扩展 XML 文档!


<anyAttribute> 元素

<anyAttribute> 元素使我们能够使用架构未指定的属性来扩展 XML 文档。

以下示例是来自名为 "family.xsd" 的 XML 架构的片段。它显示了 "person" 元素的声明。通过使用 <anyAttribute> 元素,我们可以向 "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>

现在我们要使用 "eyecolor" 属性扩展 "person" 元素。在这种情况下,即使上述模式的作者从未声明任何 "eyecolor" 属性,我们也可以这样做。

查看这个名为 "attribute.xsd" 的架构文件:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.91xjr.com"
xmlns="https://www.91xjr.com"
elementFormDefault="qualified">

<xs:attribute name="eyecolor">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:pattern value="blue|brown|green|grey"/>
    </xs:restriction>
  </xs:simpleType>
</xs:attribute>

</xs:schema>


下面的 XML 文件(称为 "Myfamily.xml")使用来自两个不同架构的组件; "family.xsd" 和 "attribute.xsd":

<?xml version="1.0" encoding="UTF-8"?>

<persons xmlns="http://www.microsoft.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:SchemaLocation="http://www.microsoft.com family.xsd
https://www.91xjr.com attribute.xsd">

<person eyecolor="green">
  <firstname>Hege</firstname>
  <lastname>Refsnes</lastname>
</person>

<person eyecolor="blue">
  <firstname>Stale</firstname>
  <lastname>Refsnes</lastname>
</person>

</persons>

上面的 XML 文件是有效的,因为架构 "family.xsd" 允许我们向 "person" 元素添加属性。

<any> 和 <anyAttribute> 元素用于制作可扩展文档!它们允许文档包含未在主 XML 模式中声明的其他元素。