定义具有相同属性和元素名称的 XSD complexType

Defining an XSD complexType with same attribute and element name

如何在 XSD 中定义一个 complexType,它可以具有同名的属性和元素?

例如:

<configuration>
   <configure name="variable1" value="val1"/>
   <configure name="variableList">
       <value>val1</value>
       <value>val2</value>
       <value>val3</value>
   </configure>
</configuration>

如何写一个XSD?

无需执行任何特殊操作即可定义具有与该元素同名的属性的元素。以下 XSD 将验证您的 XML:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="configuration">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="configure"
                    minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="value" type="xs:string"
                          minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string"/>
            <xs:attribute name="value" type="xs:string"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

如果您希望 configure 的类型根据 name 的值而变化,则使用 conditional type assignment(需要 XSD 1.1),或者,更好的是,只是区分元素名称本身(适用于 XSD 1.0 和 1.1):

XML

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:noNamespaceSchemaLocation="try.xsd">
   <configure name="variable1" value="val1"/>
   <configureList name="variable2">
       <value>val1</value>
       <value>val2</value>
       <value>val3</value>
   </configureList>
</configuration>

XSD

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="configuration">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="configure"
                    minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="name" type="xs:string"/>
            <xs:attribute name="value" type="xs:string"/>
          </xs:complexType>
        </xs:element>
        <xs:element name="configureList"
                    minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="value" minOccurs="0"
                          maxOccurs="unbounded"
                          type="xs:string"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string"/>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>