∟Testing XML Schema Location with Namespaces - JAXP
This section describes a tutorial example on how to validate an XML document with schema location assigned inside the XML document using the JAXP interface. Namespace is used in the schema and the XML document.
When a schema is assigned in an XML document with the "schemaLocation" attribute,
the assigned schema will be considered as a hint by XML processors.
In fact, you use JAXP (Java API for XML Processing) 1.4 to perform schema validation,
it will completely ignore the schema assigned in the "schemaLocation" attribute.
Let's use XsdSchemaValidator.java described earlier in this book to test this.
Test 1. If the correct version of the schema is provided, hello_xsd_default_namespace.xml
will pass the JAXP validation program:
Test 2. If the incorrect version of the schema is provided, hello_xsd_default_namespace.xml
will not pass the JAXP validation program. This test proves that XsdSchemaValidator.java
totally ignores the schema specified inside the XML document.
>java XsdSchemaValidator hello.xsd hello_xsd_default_namespace.xml
Error:
Line number: 4
Column number: 65
Message: cvc-elt.1: Cannot find the declaration of element 'p'.
Failed with errors: 1
Test 3. JAXP programs do check the namespace specified in the schema and make sure it matches
the namespace used in the XML document. See the test below:
>type hello_namespace.xsd
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://herongyang.com">
<xsd:element name="p" type="xsd:string"/>
</xsd:schema>
>type hello_xsd_namespace_wrong.xml
<?xml version="1.0"?>
<hy:p xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:hy="http://herongyang.com/x"
xsi:schemaLocation="http://herongyang.com/x hello_namespace.xsd">
Hello world!</hy:p>
>java XsdSchemaValidator hello_namespace.xsd
hello_xsd_namespace_wrong.xml
Error:
Line number: 4
Column number: 67
Message: cvc-elt.1: Cannot find the declaration of element 'hy:p'.
Failed with errors: 1