如何在XSD中为包含子元素序列的元素添加属性声明?

时间:2016-06-10 08:18:08

标签: xml xsd xsd-validation xml-validation

这是我的示例XML代码:

<Address>
        <StreetAddress></StreetAddress>
        <OtherDestination />
        <City>TORONTO</City>
</Address>

目前正在使用此XSD:

<xs:element name="Address" nillable="true">
    <xs:complexType>
        <xs:sequence minOccurs="0">
            <xs:element ref="StreetAddress" minOccurs="0"/>
            <xs:element ref="OtherDestination" minOccurs="0"/>
            <xs:element ref="City" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

我想将id属性添加到Address这样的元素..

<Address id="first">
        <StreetAddress></StreetAddress>
        <OtherDestination />
        <City>TORONTO</City>
</Address>

我应该如何更改现有的XSD以满足我的要求?

1 个答案:

答案 0 :(得分:2)

可以在xs:complexType之后的xs:sequence内添加属性声明:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           elementFormDefault="qualified">
  <xs:element name="Address">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="StreetAddress" minOccurs="0" type="xs:string"/>
        <xs:element name="OtherDestination" minOccurs="0" type="xs:string"/>
        <xs:element name="City" minOccurs="0" type="xs:string"/>
      </xs:sequence>

      <!------------------------------------------>
      <!-- This is where to declare attributes: -->
      <xs:attribute name="id" type="xs:string"/>
      <!------------------------------------------>

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

上述XSD将成功验证您的XML。