Cure Your Java XML Troubles with a Dose of Castor Oil
Now you're ready to generate some XML. As before, you read the mapping file in, but this time you create a Marshaller, handing it a java.io.Writer (in this case a StringWriter, that will store the XML for us to print.) Then you have only to set the mapping on the marshaller, and marshall the top-level object, in this case our book collection.
Mapping mapping = new Mapping(); InputStream mappingStream = Example3.class. getResourceAsStream("collection-mapping.xml"); mapping.loadMapping(new InputSource(mappingStream)); Writer stringWriter = new StringWriter(); Marshaller marshaller = new Marshaller(stringWriter); marshaller.setMapping(mapping); marshaller.marshal(col); stringWriter.close(); System.out.println(stringWriter.toString()); } catch (MarshalException e) { e.printStackTrace(); } catch (ValidationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (MappingException e) { e.printStackTrace(); } }
The resulting XML looks just like you want it:
<?xml version="1.0" encoding="UTF-8"?> <collection> <book isbn="0672323095"> <title>MySQL and JSP Web Applications</title> <author> <lastname>Turner</lastname> <firstname>James</firstname> </author> </book> <book isbn="0672324725"> <title>Struts Kick Start</title> <author> <lastname>Bedell</lastname> <firstname>Kevin</firstname> </author> <author> <lastname>Turner</lastname> <firstname>James</firstname> </author> </book> </collection>
This article only begins to scratch the surface of what Castor can do, a particularly good walkthrough of how to use mapping files with Castor can be found at: http://www.castor.org/xml-mapping.html.
About the Author
James Turner is a Senior Software Engineer at Kronos, Inc. He has written two books on Java Web Development and writes frequently on technology and software development.
Page 3 of 3