2014-01-24 26 views
12

我試圖根據給定的XML文件開發XSD語法。給定的XML文件itemList.xml如下所示。XML驗證:「此時不需要子元素」

<?xml version="1.0" encoding = "utf-8"?> 
<itemList 
    xmlns="http://www.w3schools.com" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.w3schools.com itemList.xsd" > 
    <item>spoon</item> 
    <item>knife</item> 
    <item>fork</item> 
    <item>cup</item> 
</itemList> 

itemList.xsd文件,我發展爲如下所示。

<schema 
    xmlns="http://www.w3.org/2001/XMLSchema" 
    xmlns:co="http://www.w3schools.com" 
    targetNamespace="http://www.w3schools.com" 
    elementFormDefault="qualified"> 
<simpleType name="itemType"> 
    <restriction base="string"/> 
</simpleType> 
<complexType name="itemListType"> 
    <sequence> 
     <element name="item" type="co:itemType"/> 
    </sequence> 
</complexType> 
<element name="itemList" type="co:itemListType"/> 
</schema> 

當我使用this XML validator驗證對XSD的XML,我得到的錯誤

Cvc-complex-type.2.4.d: Invalid Content Was Found Starting With Element 'item'. No Child Element Is Expected At This Point.. Line '6', Column '12'. 

看來我應該重寫我的complexTypeitemList.xsd,但我不知道該怎麼辦。非常感謝任何人可以提供幫助。

回答

22

您的itemList目前只有一個項目;這是因爲默認粒子基數爲1(minOccurs = maxOccurs = 1)。

如果您希望多於一個,那麼您需要使用適當的數字添加maxOccurs屬性;無限使用的maxOccurs =「無界」 ......像這樣:

<element name="item" type="co:itemType" maxOccurs="unbounded"/> 
8

在我來說,我得到這個消息,因爲在我的XML不匹配在我的XSD的字段的順序,我曾錯誤地逆轉最後兩個字段的順序。

雖然這不是問題中的情況,但我認爲這可能有助於其他人被標題引用到這個問題中(無疑,我將來再次引用這個問題時,我忘記了我剛學過的東西) 。