首页 > 解决方案 > 递归键值对的 XML 模式

问题描述

考虑以下 XML 示例文档,该文档包含具有键值对的变量,这些变量也可以是递归的:

<?xml version="1.0" encoding="UTF-8"?>
<environments>
    <variable>
        <key>Variable 1</key>
        <value>Value</value>
    </variable>

    <variable>
        <value>B</value>
        <key>Variable 2</key>
    </variable>

    <variable>
        <value></value>
        <key>Variable 2</key>
    </variable>

    <variable>
        <key>Variable 2</key>
        <value>
            <variable>
                <key>Foo</key>
                <value>Bar</value>
            </variable>
        </value>
    </variable>

    <variable>
        <key>Variable 2</key>
        <value>
            <variable>
                <key>Foo</key>
                <value>
                    <variable>
                        <key>Foo</key>
                        <value>Bar</value>
                    </variable>
                </value>
            </variable>
        </value>
    </variable>
</environments>

我想创建一个可以验证此结构的 XML 模式:零个或多个variable元素,key元素仅为字符串,元素仅为value字符串或嵌套变量。

到目前为止,我想出了这个:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">

  <!-- Element: Environments -->
  <xs:element name="environments">
    <xs:complexType>
      <xs:sequence maxOccurs="unbounded">
        <xs:element ref="variable"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <!-- Element: variable_type -->   
  <xs:element name="variable">
    <xs:complexType>

        <xs:all>
          <xs:element ref="key"/>
          <xs:element ref="value"/>
        </xs:all>

    </xs:complexType>
  </xs:element>

  <!-- Element: key -->
  <xs:element name="key" type="xs:string"/>

  <!-- Element: value -->
  <xs:element name="value">
    <xs:complexType mixed="true">
      <xs:sequence>
        <xs:choice>
          <xs:element minOccurs="0" maxOccurs="unbounded" ref="variable"/>
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

此架构适用于我的示例文档。但是,当涉及到 value 元素时,我非常不确定:<xs:complexType mixed="true">. 这意味着variable像这样的元素也将被视为有效(foo嵌套variable元素之前的额外字符):

    <variable>
        <key>Variable 2</key>
        <value>
            foo
            <variable>
                <key>Foo</key>
                <value>Bar</value>
            </variable>
        </value>
    </variable>

我的问题:如何确定该value元素是另一个variable元素(复杂类型)还是只是一个字符串?

标签: xmlrecursionxsdxsd-1.1

解决方案


XSD 中的混合内容实际上只适用于叙述性文本文档。除了使用 XSD 1.1 断言之外,您可以对混合内容施加的有效约束很少。如果可以的话,最好避免这种内容模型。


推荐阅读