XML Schema anyAttribute 元素概述
XML Schema 的 anyAttribute 元素用于在复杂类型定义中允许任意属性出现在元素中。它提供了一种灵活的方式,允许扩展或限制元素可以包含的属性,而无需在模式中显式声明这些属性。anyAttribute 通常用于需要支持未知或动态属性的场景。
anyAttribute 的基本语法
anyAttribute 的基本语法如下:
<xs:anyAttribute
id="ID"
namespace="##any|##other|##local|##targetNamespace|URI引用列表"
processContents="lax|skip|strict"
anyAttributes="其他属性"
/>
namespace:指定允许的属性所属的命名空间。默认值为##any,表示允许任何命名空间的属性。processContents:指定如何处理属性的验证。strict(默认)要求属性必须被模式验证,lax尝试验证(如果可能),skip不验证。
使用 anyAttribute 的代码示例
示例 1:允许任何命名空间的属性
以下模式定义了一个 person 元素,允许其包含任何命名空间的属性:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
</xs:sequence>
<xs:anyAttribute/>
</xs:complexType>
</xs:element>
</xs:schema>
对应的 XML 实例可以包含任意属性:
<person gender="male" xmlns:ext="http://example.com/ext" ext:role="admin">
<name>John Doe</name>
<age>30</age>
</person>
示例 2:限制属性的命名空间
以下模式只允许来自 http://example.com/ext 命名空间的属性:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="product">
<xs:complexType>
<xs:attribute name="id" type="xs:string"/>
<xs:anyAttribute namespace="http://example.com/ext" processContents="lax"/>
</xs:complexType>
</xs:element>
</xs:schema>
有效的 XML 实例:
<product id="p123" xmlns:ext="http://example.com/ext" ext:discount="10%"/>
示例 3:使用 processContents 控制验证
以下模式允许任何命名空间的属性,但不进行验证:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="document">
<xs:complexType>
<xs:anyAttribute namespace="##any" processContents="skip"/>
</xs:complexType>
</xs:element>
</xs:schema>
XML 实例可以包含未定义的属性:
<document status="draft" author="Alice"/>
anyAttribute 的高级用法
混合使用固定属性和任意属性
可以在复杂类型中同时定义固定属性和任意属性:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order">
<xs:complexType>
<xs:attribute name="orderId" type="xs:string" use="required"/>
<xs:anyAttribute namespace="##other" processContents="lax"/>
</xs:complexType>
</xs:element>
</xs:schema>
有效的 XML 实例:
<order orderId="o456" xmlns:log="http://example.com/log" log:timestamp="2023-01-01"/>
结合 any 和 anyAttribute
可以在元素内容中同时使用 any 和 anyAttribute 实现完全灵活的 XML 结构:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="flexible">
<xs:complexType>
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
</xs:sequence>
<xs:anyAttribute/>
</xs:complexType>
</xs:element>
</xs:schema>
XML 实例可以包含任意内容和属性:
<flexible attr1="value1" attr2="value2">
<child>Content</child>
<another xmlns="http://example.com/ns">More content</another>
</flexible>
注意事项
- 使用
anyAttribute会降低模式对文档的约束能力,应谨慎使用。 - 当
processContents设置为strict时,必须确保属性在可用的模式中定义。 - 命名空间限制可以帮助控制属性的来源,避免不可控的扩展。
- 在严格验证的场景中,建议使用
lax而非skip,以保持一定程度的验证。
通过合理使用 anyAttribute,可以在保持 XML 文档灵活性的同时,提供必要的结构约束。

268

被折叠的 条评论
为什么被折叠?



