我一直试图弄清楚如何在将 XML 文件加载到应用程序中时使用 XML Schema 来验证它们。我已经完成了那部分工作,但我似乎无法让架构将根元素以外的任何内容识别为有效。例如,我有以下 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);