Java Reference
In-Depth Information
we do is a simple string comparison of the start of the document
G
. You could also
use Java regular expressions to do some further
XML
string-based checks; next, we use
an important
XML
feature:
XML
validation.
13.7.2
Validating an XML response
If you can parse an
XML
document, you know that it's
well formed,
meaning that the
XML
syntax is obeyed, nothing more.
XML
provides a standard called
XML
Schema,
which you use to define a
vocabulary
of
XML
, specifying which elements and attributes
make up a
valid
document. In this next example, the schema is stored in a file called
personal.xsd. Listing 13.11 uses the standard Java
XML
API
s to validate the
XML
docu-
ment returned from a server call against an
XML
Schema.
Listing 13.11
A validating XML service test
@Test
public void testGetXmlAndValidateXmlSchema() throws
IOException, ParserConfigurationException, SAXException {
HttpClient httpClient = new HttpClient();
GetMethod get = new GetMethod(
Document document;
try {
httpClient.executeMethod(get);
InputStream input = get.getResponseBodyAsStream();
// Parse the XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
document = parser.parse(input);
} finally {
get.releaseConnection();
}
B
// Create a SchemaFactory capable of understanding XSD schemas
SchemaFactory factory = SchemaFactory.newInstance(
XMLConstants.W3C_XML_SCHEMA_NS_URI);
C
// Load the XSD schema in a Schema instance
Source schemaFile = new StreamSource(new File(
"src/main/webapp/personal.xsd"));
Schema schema = factory.newSchema(schemaFile);
D
// Create a Validator, which we use to validate the document
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
}
This example starts as the previous one did, but after the test executes the
HTTP
GET
method, we read the server response directly with an
XML
parser
b
. If the
DOM
docu-
ment parses successfully, we know the document is well formed, a nice sanity check. If
we don't get a valid
XML
document from the server, we might have a server error mes-
sage in the response or a bug in server-side
XML
document generation. We can now
move to the meat of the test,
XML
validation. We create a schema factory for the kind
E