Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB - can class containment be flattened when marshalling to XML?

Say, I have two classes:

@XmlRootElement
class A {
    @XmlElement
    String propertyOfA;
    @XmlElement
    B b;
}

class B {
    @XmlElement
    String propertyOfB;
} 

JAXB returns an XML formatted in the according way:

<a>
  <propertyOfA>valueA</propertyOfA>
  <b>
    <propertyOfB>valueB</propertyOfB>
  </b>
</a>

My question is how to flatten the hierarchy in the XML? So that I have:

<a>
  <propertyOfA>valueA</propertyOfA>
  <propertyOfB>valueB</propertyOfB>
</a>

Can this be done with annotations?

At the moment I am thinking to create a kind of wrapper class for A, that would have fields built the way I want to see them in the XML. Is there a better way?

like image 963
Alvis Avatar asked Dec 02 '11 19:12

Alvis


2 Answers

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

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

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

@XmlRootElement
class A {
    @XmlElement
    String propertyOfA;

    @XmlPath(".")
    B b;
}

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
like image 125
bdoughan Avatar answered Nov 04 '22 02:11

bdoughan


It's been a while for me, but let me give it a crack:

@XmlRootElement
class A {
    @XmlElement
    String propertyOfA;
    @XmlElement(name="propertyOfB")
    B b;
}
@XmlType(name="")
class B {
    @XmlValue
    String propertyOfB;
} 

Edit: disclaimer- I havn't compiled or tried this. But I believe it's how you do it.

like image 43
Daniel Moses Avatar answered Nov 04 '22 01:11

Daniel Moses