2009-06-22 17 views
1

我一直在試圖弄清楚如何在將XML文件加載到應用程序中時使用XML模式來驗證XML文件。我已經有這個部分的工作,但我似乎無法讓模式識別除根元素以外的任何其他內容。舉例來說,我有以下XML文件:XSD中的子元素和命名空間

<fun xmlns="http://ttdi.us/I/am/having/fun" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://ttdi.us/I/am/having/fun 
          test.xsd"> 
    <activity>rowing</activity> 
    <activity>eating</activity> 
    <activity>coding</activity> 
</fun> 

以下的(從視覺上公認生成的編輯器,我只是一個凡人)XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema targetNamespace="http://ttdi.us/I/am/having/fun" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://ttdi.us/I/am/having/fun"> 
    <xsd:element name="fun" type="activityList"></xsd:element> 

    <xsd:complexType name="activityList"> 
     <xsd:sequence> 
      <xsd:element name="activity" type="xsd:string" maxOccurs="unbounded" minOccurs="0"></xsd:element> 
     </xsd:sequence> 
    </xsd:complexType> 
</xsd:schema> 

但是現在,使用Eclipse的內置-in(?Xerces的基礎)驗證,我得到以下錯誤:

cvc-complex-type.2.4.a: Invalid content was found starting with element 'activity'. One of '{activity}' is expected. 

那麼,如何解決我的XSD,使其...作品?到目前爲止,我所看到的所有搜索結果似乎都是這樣說的:「...所以我只關閉了驗證」或「...所以我剛剛擺脫了命名空間」,這不是我想要做的事情。

附錄:

現在,讓我們說,我改變我的模式,以這樣的:

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema targetNamespace="http://ttdi.us/I/am/having/fun" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://ttdi.us/I/am/having/fun"> 
    <xsd:element name="activity" type="xsd:string"></xsd:element> 

    <xsd:element name="fun"> 
     <xsd:complexType> 
      <xsd:sequence> 
       <xsd:element ref="activity" minOccurs="0" maxOccurs="unbounded"/> 
      </xsd:sequence> 
     </xsd:complexType> 
    </xsd:element> 
</xsd:schema> 

現在它的工作原理,但確實這個方法意味着我不允許有<actvity>在我的文檔的根?如果ref應該原樣替換,那麼爲什麼我不能用name="activity" type="xsd:string"替換ref="actvity"

額外增編:總是這樣做,否則你會花幾個小時在牆上撞你的頭:

DocumentBuilderFactory dbf; 
// initialize dbf 
dbf.setNamespaceAware(true); 

回答

1

此XSD驗證正確here

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema targetNamespace="http://ttdi.us/I/am/having/fun" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://ttdi.us/I/am/having/fun"> 

    <!-- definition of simple element(s) --> 
    <xsd:element name="activity" type="xsd:string"></xsd:element> 

    <!-- definition of complex element(s) --> 
    <xsd:element name="fun"> 
    <xsd:complexType> 
     <xsd:sequence> 
     <xsd:element ref="activity" maxOccurs="unbounded" minOccurs="0"/> 
     </xsd:sequence> 
    </xsd:complexType> 
    </xsd:element> 

</xsd:schema> 
+0

如此,是把所有的文檔根目錄中的那些元素是「正確的」/被接受的事情?首先看它看起來有點有趣。 – 2009-06-22 18:54:29