2014-08-28 73 views
0

我一直在阅读各种资源并尝试各种方法,但我仍然无法做到这一点。如何在XSD中声明一个元素的属性

说出XML是:

<?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> 

我应该怎么写的XSD?

以下是我有:

<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> 

我能得到该文件最初被验证。当我尝试添加并声明id属性时,验证失败。任何线索?

回答

2

你不需要extensionanimal下型,只是

<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> 

属性声明的复杂类型没有明确的超类型(即没有0​​或complexContent)下complexType直接进入,而且必须任何sequence(或choice或其他)。

+0

谢谢。我现在开始工作了。我从来没有想到这个命令很重要。 – 2014-08-28 09:51:22

相关问题