dcsimg
June 18, 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 =
            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



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.

Sitemap

×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date