You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何扩展XSD schema为xs:documentation元素新增自定义type属性

实现方案

你要实现给xs:documentation添加type属性的需求,有两种常用方案,可根据实际需求选择:

方案一:直接使用(无属性取值约束场景)

W3C XML Schema 标准中对xs:documentation元素的定义本身就包含了xs:anyAttribute声明,且处理规则为lax,也就是说你可以直接在xs:documentation上添加任意自定义属性,不需要做任何额外修改,所有兼容标准的XSD处理器都不会报错,你问题中给出的示例代码本身就是合法可直接使用的:

<xs:annotation>
   <xs:documentation type="doc">
       My documentation....
   </xs:documentation>
   <xs:documentation type="example">
       My first example...
   </xs:documentation>
   <xs:documentation type="example">
       My second example...
   </xs:documentation>
   <xs:documentation type="tip">
        My tip.
   </xs:documentation>
</xs:annotation>

如果不需要对type的取值做强制校验,用这个方案就足够了。

方案二:添加取值约束(需校验属性合法性场景)

如果你需要限制type属性只能取doc/example/tip这几个预设值,避免写错,可以通过扩展XML Schema的内置定义实现,步骤如下:

  1. 为自定义属性声明专属命名空间,避免和标准属性冲突
  2. 定义type属性的枚举取值约束
  3. 在自己的业务XSD中引入命名空间即可使用带约束的属性

示例扩展Schema代码如下:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:my="http://your-custom-ns.com/doc-type"
           targetNamespace="http://your-custom-ns.com/doc-type"
           elementFormDefault="qualified">

  <!-- 定义type属性的合法取值枚举 -->
  <xs:attribute name="type">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:enumeration value="doc"/>
        <xs:enumeration value="example"/>
        <xs:enumeration value="tip"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:attribute>

</xs:schema>

在你自己的XSD文件中引用上述自定义命名空间即可使用带约束的type属性:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:my="http://your-custom-ns.com/doc-type">

  <!-- 使用带自定义type属性的documentation -->
  <xs:annotation>
    <xs:documentation my:type="doc">文档内容</xs:documentation>
    <xs:documentation my:type="example">示例内容</xs:documentation>
    <xs:documentation my:type="tip">提示内容</xs:documentation>
  </xs:annotation>

  <!-- 其余你的XSD定义内容 -->

</xs:schema>

这种方案下你可以用自定义的扩展Schema来校验你编写的XSD文件,一旦my:type的取值不在枚举范围内就会抛出校验错误,适合大型项目中需要统一规范文档分类的场景。

内容的提问来源于stack exchange,提问作者César Zea Gómez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:09:03