【问题标题】:XML Schema element with attribute and anyType children具有属性和 anyType 子项的 XML Schema 元素
【发布时间】:2013-12-09 07:01:51
【问题描述】:

我对 XML 模式不太熟悉,但我希望有一个模式允许元素具有任何类型的子元素的名称属性。 例如元素 myType:

<myType name="type1">
    <value>my value</value>
    <country>US</country>
</myType>

我试过了(显然不行):

<xsd:element name="myType" minOccurs="1" maxOccurs="unbounded" type="xsd:anyType">
    <xsd:complexType>
        <xsd:attribute name="name" type="xsd:string" use="required"/>
    </xsd:complexType>
</xsd:element>

【问题讨论】:

    标签: xml xsd xsd-validation


    【解决方案1】:

    此 XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <myType name="type1">
        <value>my value</value>
        <country>US</country>
    </myType>
    

    根据此 XSD 有效:

    <?xml version="1.0" encoding="utf-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="myType">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:any processContents="lax" maxOccurs="unbounded"/>
          </xsd:sequence>
          <xsd:attribute name="name" type="xsd:string" use="required"/>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    

    说明:

    • xsd:any 项允许任何元素成为myType 的子元素。
    • xsd:any/@processContents="lax" 设置“指示 XML 处理器在可行的基础上验证元素内容:它 将验证它可以获得架构的元素和属性 信息,但不会为无法获取的信息发出错误信号 任何架构信息。”

    【讨论】:

    • 嗨,我有同样的问题,但上面的代码我有Character content other than whitespace is not allowed because the content type is 'element-only' 错误。答案对某人有用吗?
    • 答案适用于问题中的 XML,它只有元素子元素。如果您希望支持任何文本和元素子元素的组合,请将mixed="true" 添加到xsd:complexType
    猜你喜欢
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多