2014-01-17 60 views
2

我有以下XML元素。 我需要驗證參數屬性是否只持有Y或N在下面的XML元素使用XSD驗證XML元素屬性值

<Test Script="abc.sh" Parameter="Y"/> 
       **OR** 
<Test Script="abc.sh" Parameter="N"/> 

我的XSD是:

<xs:element name="Test" minOccurs="0"> 
     <xs:complexType> 
      <xs:attribute name="Script" type="xs:string" use="required"/> 
      <xs:attribute name="Parameter" type="xs:string" use="optional"/>      
     </xs:complexType> 
    </xs:element> 

目前該XSD不驗證參數是否持有YN

回答

4

需要定義具有simpleType一個attribute,以實施一組定義的值的屬性值是構件表示restriction

想象一下,你有以下的XML:

<?xml version="1.0"?> 
<Test Script="path/to/script" Parameter="Y" xmlns="http://www.example.org" /> 

可以強制他們type屬性具有使用該XSD一個的foobar值:

<?xml version="1.0"?> 
<xsd:schema 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:tns="http://www.example.org" 
    targetNamespace="http://www.example.org" 
    elementFormDefault="qualified" 
    attributeFormDefault="unqualified" 
> 
    <xsd:element name="Test"> 
     <xsd:complexType> 
     <xsd:attribute name="Script" type="xsd:string" use="required"/> 
     <!-- the following has no type attribute. It's type is 
      defined in the simpleType child --> 
     <xsd:attribute name="Parameter" use="optional"> 
      <xsd:simpleType> 
      <!-- define a set of xsd:strings 
       as possible values --> 
      <xsd:restriction base="xsd:string"> 
       <xsd:enumeration value="Y"/> 
       <xsd:enumeration value="N"/> 
      </xsd:restriction> 
      </xsd:simpleType> 
     </xsd:attribute> 
     </xsd:complexType> 
    </xsd:element> 
</xsd:schema> 
+0

我用;你給出了 有什麼區別? – logan

+0

@logan只是個人喜好。如果你願意,你可以用你的'xs'替換我的'xsd'。您正在使用的前綴是在架構頭部的'xmlns:xsd = ..'或'xmlns:xs'中定義的 – hek2mgl

+0

現在我只使用xs,但它說org.xml.sax.SAXParseException:前綴「 xsd:「xsd:simpleType」沒有被綁定 – logan

2

你必須定義參數屬性這樣

 <xs:simpleType name="yesno"> 
      <xs:restriction base="xs:string"> 
       <xs:enumeration value="Y" /> 
       <xs:enumeration value="N" /> 
      </xs:restriction> 
     </xs:simpleType> 



     <xs:attribute name="Parameter" type="xs:yesno" use="optional"/> 
+0

無效參數的錯誤信息爲「原因:cvc-e numeration-valid:值'YY'對於枚舉'[Y,N]'不是方面有效的。 「是不是可以在錯誤信息中顯示XML屬性名稱? – logan

+0

我不確定你是如何解析你的xml文檔的。你可能想要檢查API文檔(如果以編程方式解析)或用戶指南(如果使用任何工具) – IndoKnight

1

試試這個:

<xs:element name="Test" maxOccurs="unbounded"> 
       <xs:complexType> 
          <xs:attribute name="Script"> 
           <xs:simpleType> 
            <xs:restriction base="xs:string"> 
             <xs:enumeration value="abc.sh"> 
             </xs:enumeration> 
            </xs:restriction> 
           </xs:simpleType> 
          </xs:attribute> 
           <xs:attribute name="Parameter"> 
           <xs:simpleType> 
            <xs:restriction base="xs:string"> 
             <xs:pattern value="Y|N" > 
             </xs:pattern> 
            </xs:restriction> 
           </xs:simpleType>  
           </xs:attribute> 
       </xs:complexType> 
</xs:element>