Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...