I have the following XML structure, which is modelling a single concept across multiple XML elements. This format is not in my control.
<Output>
<Wrapper>
<Channel>
<id>1</id>
<type>x</type>
</Channel>
<Channel>
<id>2</id>
<type>y</type>
</Channel>
<ChannelName>
<id>1</id>
<name>Channel name</name>
</ChannelName>
<ChannelName>
<id>2</id>
<name>Another channel name</name>
</ChannelName>
</Wrapper>
</Output>
I want to model this in a database that I do have control over and can have a more simple Channel
table with id
, type
and name
fields. Therefore I would like to unmarshal into a single List<Channel>
on the Wrapper
class.
Can this be done with @Xml...
annotations automatically? I am currently using JAXB to unmarshal into separate @XmlElement(name="Channel")
and @XmlElement(name="ChannelName")
class lists and then post-processing the transient ChannelName/name
on the Channel
but I am thinking there must be an easier automated way to map these elements. Or is it a job for XSLT?
It might help to know that the XML is coming in as an HTTP file POST file and I'm using Spring 3, Java and Hibernate. I'm hoping something in EclipseLink JAXB (MOXy) might help :)
You can save your coding time by automating this process in JAXB:
Create a XML schema for your XML using the link below as save it as output.xsd file: http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx
Run the batch script file (name it as output.bat) below from the project root folder (.) using JDK as only JDK has xjc.exe tool (fill in the necessary details):
where...
Example:
let say project folder is organized as follows:
Run following at command prompt from (.):
It will create a few files:
Then, you can create a few useful methods below to manipulate
Output
objects:@XmlElementWrapper will do the job:
For more advanced cases you can use the @XmlPath extension in EclipseLink JAXB (MOXy):
Here is what I have so far. I'm still trying to eliminate the need for the helper objects. This example requires EclipseLink JAXB (MOXy).
Model Objects
Your model objects are:
and:
Helper Objects
My current solution involves some helper objects:
and:
Demo Code