Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java Xml to POJO mapping/binding?

Tags:

java

xml

jibx

I'm trying to figure out the simplest way to map an xml file to to a plain old java object.

Note: That in my example the xml doesn't quite match up with my intended POJO.

///////// THE XML
<?xml version="1.0" encoding="UTF-8"?>
<Animal>
  <standardName>
    <Name>Cat</Name>
  </standardName>
  <standardVersion>
    <VersionIdentifier>V02.00</VersionIdentifier>
  </standardVersion>
</Animal>


////// THE INTENDED POJO
class Animal
{
 private String name;
 private String versionIdentifier;
}

Regular JAXB (with annotations) won't work as the JAXM Element name annotations don't allow me to specifiy nested elements. (i.e. standardName/Name).

I've looked at Jibx but it seems overly complicated, and no full examples are provided for what I want to do.

Castro seems like it would be able to do what I want (using mapping files), but I wonder if there are any other possible solutions. (Possibly that would allow me to skip mapping files, and just allow me to specify everything in annotations).

Thanks

like image 526
vicsz Avatar asked Oct 30 '09 19:10

vicsz


1 Answers

EclipseLink JAXB (MOXy) allows you to do the path based mapping that you are looking for:

@XmlRootElement 
class Animal 
{ 
 @XmlPath("standardName/Name/text()")
 private String name; 

 @XmlPath("standardVersion/VersionIdentifier/text()");
 private String versionIdentifier; 
} 

For more information see:

  • http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html
  • http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
  • http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/MOXyExtensions

EclipseLink also allows the metadata to be specified using an external configuration file:

  • http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/ExternalizedMetadata
like image 154
bdoughan Avatar answered Sep 21 '22 18:09

bdoughan