简体   繁体   中英

How to declare an attribute for an element in XSD

I have been reading various sources and trying out various methods but I still can't get this right.

Say the XML is:

<?xml version="1.0"?>

<zoo xmlns="http://www.example.com"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.example.com zoo.xsd">
   <animal id="l123444">
      <name>Mighty</name>
      <type>lion</type>
      <kg>135</kg>
   </animal>

   <animal id="b343234">
      <name>Lucky</name>
      <type>bear</type>
      <kg>205</kg>
   </animal>
</zoo>

How should I write the XSD?

Here is what I have got:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.example.com"
           xmlns="http://www.example.com"
           elementFormDefault="qualified">

<xs:element name="zoo"><xs:complexType><xs:sequence>
   <xs:element name="animal" maxOccurs="unbounded">
      <xs:complexType>
         <xs:extension base="xs:string">
            <xs:attribute name="id"/>
         </xs:extension>
         <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="type"><xs:simpleType>
                <xs:restriction base="xs:string">
                   <xs:enumeration value="lion"/>
                   <xs:enumeration value="bear"/>
                   <xs:enumeration value="tiger"/>
                </xs:restriction>
            </xs:simpleType></xs:element>
            <xs:element name="kg"><xs:simpleType>
               <xs:restriction base="xs:integer">
                  <xs:minInclusive value="10"/>
                  <xs:maxInclusive value="5000"/>
               </xs:restriction>
            </xs:simpleType></xs:element>
         </xs:sequence>
      </xs:complexType>
   </xs:element>
</xs:sequence></xs:complexType></xs:element>

</xs:schema>

I could get the document validated initially. When I tried to add and declare the id attribute, the validation failed. Any clue?

You don't need the extension under the type of animal , just

<xs:element name="animal" maxOccurs="unbounded">
  <xs:complexType>
     <xs:sequence>
       <!-- child elements -->
     </xs:sequence>
     <xs:attribute name="id" type="xs:string"/>
   </xs:complexType>
</xs:element>

Attribute declarations for a complex type with no explicit supertype (ie without simpleContent or complexContent ) go directly under the complexType , and must be after any sequence (or choice or whatever).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM