1

我的 XML 文件如下所示:

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

我想对name标签的属性应用正则表达式限制,<field/>无论它是孩子还是孙子或孙子等等。我已经尝试了以下代码,但是当它是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>
4

1 回答 1

0

您实际上可以在 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>
于 2016-07-13T00:14:03.870 回答