October 23, 2018
Hot Topics:

Cure Your Java XML Troubles with a Dose of Castor Oil

  • December 21, 2006
  • By James Turner
  • Send Email »
  • More Articles »

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 =
        mapping.loadMapping(new InputSource(mappingStream));
        Writer stringWriter = new StringWriter();
        Marshaller marshaller = new Marshaller(stringWriter);
    } catch (MarshalException e) {
    } catch (ValidationException e) {
    } catch (IOException e) {
    } catch (MappingException e) {

The resulting XML looks just like you want it:

<?xml version="1.0" encoding="UTF-8"?>
	<book isbn="0672323095">
		<title>MySQL and JSP Web Applications</title>
	<book isbn="0672324725">
		<title>Struts Kick Start</title>

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

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.


Thanks for your registration, follow us on our social networks to keep up-to-date