// get the output writter to write the XML content
StringWriter xmlOutput = new StringWriter();
// create an instance of XML Schema marshaller
AbstractMarshaller marshaller = (AbstractMarshaller)Marshaller.FACTORY.getInstance();
// we need to specify what elements are top most (roots) providing namespace URI, prefix and local name
marshaller.addRootElement("http://example.org/ns/books/", "", "book");
// declare default namespace
marshaller.declareNamespace(null, "http://example.org/ns/books/");
// add schema location by declaring xsi namespace and adding xsi:schemaReader attribute
marshaller.declareNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
marshaller.addAttribute("xsi",
"schemaReader",
"string",
"http://example.org/ns/books/ resources/book/books.xsd"
);
// create an instance of Object Model Provider with no book
ObjectModelProvider provider = new BookObjectProvider();
// marshall Book instance passing it as an argument instead of using the one that is returned by the BookObjectProvider
marshaller.marshal(getResourceUrl("xml/book/books.xsd").toString(), provider, book, xmlOutput);
String xml = xmlOutput.getBuffer().toString();
if(log.isTraceEnabled())
{
log.debug("marshalled with " + marshaller.getClass().getName() + ": " + xml);
}
checkMarshalledBook(xml, book);
}