Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind child element attributes to fields with JAXB?

Tags:

java

xml

jaxb

Given the following XML

<mappings>
  <map>
     <source srcAttr="oof">foo</source>
     <target trgAttr="rab">bar</target>
  </map>
  <map>
    ...

Is it possible with JAXB to unmarshal the <map> elements into a single class Map containing values and attributes of <source> and <target>?

@XmlRootElement
class Map {

   @XmlElement
   String source;

   @???
   String srcAttr;

   @XmlElement
   String target;

   @???
   String trgAttr;
}

I don't want to create extra classes for Source and target.

like image 864
Udo Avatar asked Jul 02 '13 10:07

Udo


2 Answers

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

You could use MOXy's @XmlPath extension to handle this use case:

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Map {

   String source;

   @XmlPath("source/@srcAttr")
   String srcAttr;

   String target;

   @XmlPath("target/@trgAttr")
   String trgAttr;

}

For More Information

  • http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
  • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
  • http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html
like image 151
bdoughan Avatar answered Sep 20 '22 13:09

bdoughan


Yes! Just replace ??? with @XmlAttribute annotaion.

Also this might be helpful jaxb example and this oracle examples

like image 24
Tala Avatar answered Sep 22 '22 13:09

Tala