通过 XSD 验证未知 XML 元素的后代?

Validate descendants of unknown XML elements via XSD?

我的 XML 文件看起来像:

<root>
    <template>
        <unknownTag>
            <anotherUnknownTag/>
            <anotherKnownTag/>
            <field name='price'/>
        </unknownTag>
    </template>
    <template>
        <field name='salary'/>
    </template>
    <anothorKnownTag/>
</root>

我想对标签 <field/> 的属性 name 应用正则表达式限制,无论它是子代还是孙代还是孙代等等。 我尝试了以下代码,但正则表达式仅在它是 template 标记的直接子项时才应用于元素字段。

  <xs:element name="template">
    <xs:complexType>
        <xs:complexContent>
        <xs:sequence>
            <xs:element name="field">
                <xs:complexType>
                    <xs:simpleContent>
                        <xs:extension base="xs:string">
                            <xs:attribute name="name">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:pattern value="[a-z][a-z_]*"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:attribute>
                        </xs:extension>
                    </xs:simpleContent>
                </xs:complexType>
            </xs:element>
            <xs:any processContents="lax"/>
        </xs:sequence>
    </xs:complexType>
  </xs:element>

您实际上可以在 XSD 1.0:

中表达请求的约束

XSD 1.0

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="field">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute name="name">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:pattern value="[a-z][a-z_]*"/>
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

注意:你甚至可以将root简化为

  <xs:element name="root"/>

但较长的形式不那么神秘。

有效XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <template>
        <unknownTag>
            <anotherUnknownTag/>
            <anotherKnownTag/>
            <field name="price"/>
        </unknownTag>
    </template>
    <template>
        <field name="salary"/>
    </template>
    <anothorKnownTag/>
</root>

无效XML

由于 field/@name 值与正则表达式不匹配,以下 XML 有两个有效性错误:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <template>
        <unknownTag>
            <anotherUnknownTag/>
            <anotherKnownTag/>
            <field name="price999"/>
        </unknownTag>
    </template>
    <template>
        <field name="big salary"/>
    </template>
    <anothorKnownTag/>
</root>