Search code examples
javaxmljaxbpojo

How to convert multiple POJOs to xml in required format?


We've requirement where we need to generate XML file for sending it to another system. I was looking at this example (which uses JAXB).

http://thomassundberg.wordpress.com/2010/01/19/how-to-convert-a-pojo-to-xml-with-jaxb/

However, this one converts only single POJO to xml whereas we have multiple POJOs e.g. Car/Wheel/Seats etc. that should appear in xml.

Any idea on how this can be achieved?

e.g. I would like to have something like this as final output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<car registration="abc123">
    <brand>Volvo</brand>
    <description>Sedan</description>

    <wheel>
      <brand>Ceat</brand>     
    </wheel>
</car>

Solution

  • It sounds like you're trying to convert a graph of Java objects to XML, which JAXB can do. Each object in the graph should have JAXB annotations. See http://numberformat.wordpress.com/2009/11/01/using-jaxb-to-convert-between-xml-and-pojos/.