2014-03-31 24 views
1

我有一個XML文件。我正在嘗試生成xsd模式文件。我的XML文件:XML Schema如何寫無子元素的字符串

<?xml version="1.0" encoding="UTF-8"?> 
<recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="sample.xsd" id="62378"> 

    <title>Beans On Toast</title> 
    <ingredients> 
    <item quantity="1" unit="slice">bread</item> 
    <item quantity="1" unit="can">bakedbeans</item>   
    </ingredients> 
</recipe> 

我的模式文件是:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 

<xs:element name="recipe" type="recipeType"/> 
<xs:complexType name="recipeType"> 
    <xs:sequence> 
     <xs:element name="title" type="xs:string"/> 
     <xs:element name="ingredients" type="ingredientsType"/>   
    </xs:sequence> 
    <xs:attribute name="id" type="xs:integer"/> 
</xs:complexType> 

<xs:complexType name="ingredientsType"> 
    <xs:sequence> 
     <xs:element name="item" type="itemType"/> 
    </xs:sequence>  
</xs:complexType>   

<xs:complexType name="itemType"> 
    <xs:attribute name="quantity" type="xs:integer"/> 
    <xs:attribute name="unit" type="xs:string"/> 
</xs:complexType>  
</xs:schema> 

我得到錯誤,而驗證。我知道原因。因爲我沒有定義元素項type = xs:string,因爲我必須爲屬性編寫complexType(「itemType」)。任何人都可以解決這個問題嗎?

回答

0

如果你需要屬性,你必須使用complexType。但是,如果你還需要簡單的內容,那麼你就可以在你的complexTypesimpleContent定義和使用基本簡單類型

在你的情況與屬性來擴展它,你可以做這樣的事情:

<xs:complexType name="itemType"> 
    <xs:simpleContent> 
     <xs:extension base="xs:string"> 
      <xs:attribute name="quantity" type="xs:integer"/> 
      <xs:attribute name="unit" type="xs:string"/> 
     </xs:extension> 
    </xs:simpleContent> 
</xs:complexType> 

這將允許:

<item quantity="1" unit="slice">bread</item> 

你仍然需要允許內部ingredientsType多個<item>元素。如果你可以有無限的項目,你可以使用:

<xs:complexType name="ingredientsType"> 
    <xs:sequence> 
     <xs:element name="item" type="itemType" maxOccurs="unbounded" /> 
    </xs:sequence>  
</xs:complexType> 
+0

謝謝。這裏還描述:http://www.w3schools.com/schema/schema_complex_text.asp – Nusrat

+0

你能給出另一種解釋嗎?我需要序列(標題,成分),但爲什麼我必須在下一個塊中寫入序列?否則,它會給我錯誤。 – Nusrat

0

嘗試宣告itemType爲混合(在複雜類型定義使用mixed='true')。

相關問題