XSD <anyAttribute>

创建于 2024-12-03 / 31
字体: [默认] [大] [更大]

<anyAttribute> 元素使我们能够用schema未指定的属性扩展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.w3ccoo.com"
xmlns="https://www.w3ccoo.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.w3ccoo.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模式中声明的其他元素。



0 人点赞过