Java Reference
In-Depth Information
Unmarshaller um = ctx.createUnmarshaller();
//Create instance of schema
SchemaFactory factory =
SchemaFactory.newInstance(
XMLConstants.W3C_XML_SCHEMA_NS_URI);
//Create factory, add options if necessary
Schema schema = factory.newSchema(
new StreamSource(new File(SCHEMA)));
//This sets us up for validation
um.setSchema(schema);
//Read in the XML from anywhere
//In this case it is a complete XML book as string.
StringReader sr = new StringReader(getBookXml());
//Get XML from object.
//Now that we have a schema set, this throws
//MarshalException if XML doesn't match XSD
JAXBElement<Book> b = um.unmarshal(
new StreamSource(sr), Book.class);
//We never get this far with invalid XML
//Start working with object
Book book = b.getValue();
System.console().printf("Title: %s", book.getTitle());
} catch (JAXBException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//NOTE: THIS XML FAILS VALIDATION!
private static String getBookXml(){
return "<com.soacookbook.ch02.xstream.Book>" +
"<title>On Friendship</title>" +
"<price>39.95</price>" +
"<author><firstName>Jacques</firstName>" +
"<lastName>Derrida</lastName>" +
"</author><category>PHILOSOPHY</category>" +
"</com.soacookbook.ch02.xstream.Book>";
Search WWH ::




Custom Search