XSD中的子元素和命名空间

时间:2009-06-22 17:34:45

标签: xml validation xsd xerces

当我将XML文件加载到应用程序中时,我一直在试图弄清楚如何使用XML Schema来验证XML文件。我已经有了这部分工作,但我似乎无法让模式识别除根元素之外的任何其他内容都是有效的。例如,我有以下XML文件:

<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的内置(基于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应该按原样替换,那么为什么我不能用ref="actvity"替换name="activity" type="xsd:string"

附加附件:总是这样做,否则你会花费数小时的时间在墙上敲头:

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

1 个答案:

答案 0 :(得分: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>