Warm tip: This article is reproduced from serverfault.com, please click

How to add attribute declaration in XSD for element with sequence of child elements?

发布于 2016-06-10 08:18:08

This is my sample XML code:

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

That is currently using this 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>

I want to add an attribute id to Address element like this..

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

How should I change the existing XSD to fulfill my requirement?

Questioner
Thiwanka
Viewed
0
kjhughes 2016-06-10 21:13:38

An attribute declaration can be added within xs:complexType after the 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>

The above XSD will validate your XML successfully.