<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="http://www.bts.com/pcsp"
xmlns="http://www.bts.com/pcsp" xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="Contact">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string"/>
<xs:element name="Title" type="xs:string"/>
<xs:element name="Phone" type="xs:string"/>
<xs:element name="Email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:key name="ContactKey">
<xs:selector xpath="Contact"/>
<xs:field xpath="Name"/>
</xs:key>
</xs:element>
<xs:element name="ListOfContacts">
<xs:complexType>
<xs:sequence>
<xs:element ref="Contact" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
and composed the following instance xml document:
<?xml version="1.0"?>
<ListOfContacts xmlns="http://www.bts.com/pcsp"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</ListOfContacts>
then in my java code, I tried to validate the instance document against the schema,
using a DOMParser:
DOMParser parser = null;
PcspErrorHandler h = null;
parser = new DOMParser();//DOMParserManager.instance().getParser();
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
"http://www.bts.com/pcsp http://localhost:8004/pcsp/bts.xsd");
h = new PcspErrorHandler ();
parser.setErrorHandler(h);
parser.parse(new InputSource(new StringReader(xml0)));
if (h.hasError())
{
System.out.println("\nParse failed");
System.out.println(h.getErrorMessage());
}
else
{
System.out.println("\nParse fine");
}
where xml0 is the content of the instance document, and PcspErrorHandler implements ErrorHandler
and prints error message to stdout.
The schema defines a key, the intent of which is to make sure that each Contact must have a Name,
and the Names of Contacts must be unique. In the instance document, the two Contacts have the same
Name. However, when I run my java program, the DOMParser doesn't complain, even though the two
Contacts have the same Name. Moreover, when I removed the content between the Name tags, i.e.
<Name></Name>, the parser still doesn't complain.
What am I doing wrong? Please help. Thanks.
-Shengyou
