【问题标题】:Is it possible to combine explicit attributes validation and anyAttribute是否可以结合显式属性验证和 anyAttribute
【发布时间】:2011-06-07 10:19:07
【问题描述】:

是否可以在 XML 模式中定义必须有一些特定的 XML 属性,同时我想允许将来扩展这个列表?

在这里,如果我们有以下 XML 声明的假设部分:

<xs:element name="MyTypeInstance" type="MyType" />

<xs:complexType name="MyType">
  <xs:attribute name="FirstAttr" type="xs:int" use="required"/>
  <xs:attribute name="SecondAttr" type="xs:string" use="required"/>
</xs:complexType>

那么根据这个模式,下面的 XML 文档片段是有效的:

<MyType firstAttr="123" secondAttr="abc" />

我想要的是能够成功验证以下 XML 片段:

<MyType firstAttr="123" secondAttr="abc" ThirdAttr="some new value" />

两个主要问题是:

  1. 我不想每次需要引入一些新属性时都更改 XML 架构,因为我们不想强制所有客户端更新到我们软件的最新版本,其中一些不长时间更新他们的应用;
  2. 我不能只在 XML 模式中使用 anyAttribute,因为我想在使用 XML 文档之前对其进行验证。如果我只指定anyAttribute 元素,那么我就不会知道缺少一些必需的属性。据我了解,XML 不允许在架构中使用 attributeanyAttribute 元素(至少我无法使用 .net XmlDocument 类使此类架构正常工作)。

如果可以使用attribute 元素显式指定一些属性将是理想的,所以我会确切地知道这些属性存在于 XML 文档中,但同时我会让扩展 XML 文档使用anyAttribute 元素。

怎么做?

【问题讨论】:

    标签: xml xsd xml-attribute


    【解决方案1】:

    xs:anyattributeprocessContents 值可以是strictlaxskipstrict 是默认值。

    • strict: 必须有相应的全局属性声明,并且该属性将根据该声明进行验证
    • lax:如果有对应的全局属性声明,验证属性;否则跳过它
    • skip:即使有声明也不验证属性

    如果你的下一个版本的架构看起来像

    <xs:complexType name="MyType">
      <xs:attribute name="FirstAttr" type="xs:int" use="required" />
      <xs:attribute name="SecondAttr" type="xs:string" use="required" />
      <xs:attribute name="ThirdAttr" type="xs:string" use="required" />
      <xs:anyAttribute processContents="lax" />
    </xs:complexType>
    

    (您没有使用全局属性),那么skip 可能最好确保添加的属性不会意外地针对碰巧具有相同名称和可能不同类型的全局属性声明进行验证。

    【讨论】:

      【解决方案2】:

      好的,我已经解决了这个问题。架构可能如下所示:

      <xs:complexType name="MyType">
        <xs:attribute name="FirstAttr" type="xs:int" use="required" />
        <xs:attribute name="SecondAttr" type="xs:string" use="required" />
        <xs:anyAttribute processContents="lax" />
      </xs:complexType>
      

      关键是要指定processContents="lax"processContents="skip"。如果省略将processContents 设置为laxskip,则验证失败。如果有人知道这背后的逻辑,请放一些cmets。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-30
        • 2013-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多