How to map an XML to Java objects by XPaths?
Given the XML example:
<fooRoot>
<bar>
<lol>LOLOLOLOL</lol>
</bar>
<noob>
<boon>
<thisIsIt></thisIsIt>
</boon>
</noob>
</fooRoot>
Which should be mapped to:
class MyFoo {
String lol;
String thisIsIt;
Object somethingUnrelated;
}
Constraints:
- XML should not be transformed, it is provided as a parsed org.w3c.dom.Document object.
- Class does not and will not map 1:1 to the XML.
- I'm only interested to map specific paths of the XML to specific fields of the object.
My dream solut开发者_运维百科ion would look like:
@XmlMapped
class MyFoo {
@XmlElement("/fooRoot/bar/lol")
String lol;
@XmlElement("/noob/boon/thisIsIt")
String thisIsIt;
@XmlIgnore
Object somethingUnrelated;
}
Does anything likewise exists? What I've found either required a strict 1:1 mapping (e.g. JMX, JAXB) or manual iteration over all fields (e.g. SAX, Commons Digester.)
JiBX binding definitions come the nearest to what I'm lokking for. However, this tool is ment to marshall/unmarshall complete hierarchy of Java objects. I only would like to extract parts of an XML document into an existing Java bean at runtime.
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You can do this with MOXy:
@XmlRootElement(name="fooRoot")
class MyFoo {
@XmlPath("bar/lol/text()")
String lol;
@XmlElement("noob/boon/thisIsIt/text()")
String thisIsIt;
@XmlTransient
Object somethingUnrelated;
}
For More Information
- http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
- http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html
- http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html
- http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
Try XStream. It's super easy. Hope it helps! I don't have time now for a full example :)
One option could be write a custom annotation which will take the XPath expression as input and do the bindings.
精彩评论