【问题标题】:Restrict XSD such that it does not allow attribute on root element限制 XSD,使其不允许根元素上的属性
【发布时间】:2018-08-17 22:34:01
【问题描述】:

我需要使用以下 XSD 验证 XML

<xs:element name="root" type="rootType"/>
<xs:element name="names" type="nameType"/>
    <xs:complexType name="rootType" mixed="true">
        <xs:sequence>
            <xs:choice minOccurs="0" maxOccurs="unbounded">                
                <xs:element name="names" minOccurs="0" maxOccurs="unbounded" type="nameType"/>
                <xs:element name="root" minOccurs="0" maxOccurs="unbounded" type="rootType"/>                
            </xs:choice>
        </xs:sequence>
        <xs:attribute name="name" type="xs:string"/>
    </xs:complexType>

    <xs:complexType name="nameType" mixed="true">
        <xs:sequence>
            <xs:choice minOccurs="0" maxOccurs="unbounded">                
                <xs:element name="names" minOccurs="0" maxOccurs="unbounded" type="nameType"/>
                <xs:element name="root" minOccurs="0" maxOccurs="unbounded" type="rootType"/> 
            </xs:choice>
        </xs:sequence>
        <xs:attribute name="name" type="xs:string"/>
    </xs:complexType>

这样,XSD 不应允许 XML 中的根元素具有“名称”属性。

例如:XSD 应将以下 XML 视为有效

<root>
<names name="abc"></names>
<root name="xyz"></root>
</root>

以下内容无效,因为 xml 的根元素具有 name 属性。

<root name="rootElement">
<names name="abc"></names>
<root name="xyz"></root>
</root>

但是,如果同一个元素作为子元素出现,那么它可以有一个名称属性。请让我们知道使用 XSD 是否可行,如果可行,我们该怎么做?

【问题讨论】:

  • 在您继续提出新问题之前,请返回您的旧问题并accept那些有帮助的答案。如果没有答案对您有帮助,请阅读 How to Ask 和 help center。谢谢。

标签: xml xsd schema xsd-validation


【解决方案1】:

定义不带名称属性的rootType:

<xs:complexType name="rootTypeWithoutName" mixed="true">
        <xs:sequence>
            <xs:choice minOccurs="0" maxOccurs="unbounded">                
                <xs:element name="names" minOccurs="0" maxOccurs="unbounded" type="nameType"/>
                <xs:element name="root" minOccurs="0" maxOccurs="unbounded" type="rootTypeWithName"/>                
            </xs:choice>
        </xs:sequence>
    </xs:complexType>

然后定义一个允许名字的扩展类型:

<xs:complexType name="rootTypeWithName" mixed="true">
  <xs:extension base="rootTypeWithoutName">
   <xs:attribute name="name" type="xs:string"/>
  </xs:extension>
</xs:complexType>

在根的全局元素声明中,使用type="rootTypeWithoutName"。在嵌套根元素的本地元素声明中(如上所示),使用类型rootTypeWithName。

这个我没有测试过,所以可能有语法错误,但原理应该是合理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多