2009-06-22 61 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

相关问题