Java Reference
In-Depth Information
}
}
Here the validation fails. Because your XML was originally generated from XStream, which
caused the package name to prepend the root element name in the generated XML, your
root element is com.soacookbook.ch02.xstream.Book . This is not valid. So a
javax.xml.bind.UNMarshalException is thrown, and processing stops immediately. Here
is the output:
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration
of element
'com.soacookbook.ch02.xstream.Book'.]
So let's go ahead and fix the XML content so that it will validate. Note that it is not enough to
simply remove the package name and lowercase the “book” element. The XML needs to spe-
cify the namespace it uses for these elements and types just as specified in the schema to actu-
ally be valid. But there are more things still wrong with it. You also need to put the elements in
the correct order. The <sequence> element used in the schema means that content is expected
in the specified order. That's the reason that the JAXB XmlType mapping annotation provides
the order attribute. So you'll have to rearrange the XML to make the proper sequence. Finally,
the author tag is invalid because this particular schema has specified it as a simpleType , so it
must contain only a string and not child elements.
So to fix the XML, substitute the following getBookXml method that gives you a book XML
instance that validates against the Venetian Blind schema example that you defined earlier:
//This is valid according to the schema
private static String getBookXml(){
return "<b:book xmlns:b='http://ns.soacookbook.com/
venetianblind'>" +
"<title>On Friendship</title>" +
"<author>Jacques Derrida</author>" +
"<category>PHILOSOPHY</category>" +
"<price>39.95</price>" +
"</b:book>";
}
As you might hope, the process is identical whether you're marshaling or unmarshaling. So
that's all there is to using simple schema validation. There are a few more advanced options
that you can use during validation, such as collecting events emitted by the parser so you can
capture more information than just whether you passed or not, and then make that data avail-
Search WWH ::




Custom Search