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

时间:2015-07-31 11:38:56

标签: xml xsd

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

例如:

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

怎么能为此写一个XSD?

1 个答案:

答案 0 :(得分:2)

定义具有与元素同名的属性的元素没有什么特别之处。以下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>