I've been trying to figure out how to use an XML Schema to validate XML files as I load them into an application. I've got that part working, but I can't seem to get the schema to recognise anything other than the root element as valid. For instance, I have the following XML file:
<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>
with the following (admittedly generated from the visual editor—I am but a mere mortal) 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>
But now, using Eclipse's built-in (Xerces-based?) validator, I get the following error:
cvc-complex-type.2.4.a: Invalid content was found starting with element 'activity'. One of '{activity}' is expected.
So how do I fix my XSD so that it…works? All the search results I've seen so far seem to say "…so I just turned off validation" or "…so I just got rid of namespaces" and that's not something I want to do.
ADDENDUM:
Now let's say I change my schema to this:
<?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>
Now it works, but does that method mean that I'm allowed to have <actvity>
at the root of my document? And if the ref
should just be substituted as-is, then why can't I replace ref="actvity"
with name="activity" type="xsd:string"
?
ADDITIONAL ADDENDUM: ALWAYS do this, or else you will spend hours and hours banging your head on a wall:
DocumentBuilderFactory dbf;
// initialize dbf
dbf.setNamespaceAware(true);