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

孤街醉人 提交于 2019-12-01 08:08:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37743275/how-to-add-attribute-declaration-in-xsd-for-element-with-sequence-of-child-eleme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!