Search code examples
javaxmlserializationxstream

Wrapping xml output in XStream with another element


I have this class:

Class B {
  private String D;
  private String E;
}

Using XStream, I would like to generate XML like this, where elements A and B are generated in the XML, even though they don't exist in the java.:

<A>
        <B>
                <C>
                        <D/>
                        <E/>
                </C>
        </B>
</A>

Possible?


Solution

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

    Since you are looking for an annotation based solution, you may be interested in the @XmlPath extension in MOXy.

    B

    The @XmlPath annotation allows you to specify your mapping as an XPath.

    package forum11334385;
    
    import javax.xml.bind.annotation.*;
    import org.eclipse.persistence.oxm.annotations.XmlPath;
    
    @XmlRootElement(name="A")
    @XmlAccessorType(XmlAccessType.FIELD)
    class B {
    
        @XmlPath("B/C/D/text()")
        private String D;
    
        @XmlPath("B/C/E/text()")
        private String E;
    
    }
    

    jaxb.properties

    To specify MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).

    javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
    

    Demo

    package forum11334385;
    
    import java.io.File;
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(B.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            File xml = new File("src/forum11334385/input.xml");
            B b = (B) unmarshaller.unmarshal(xml);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(b, System.out);
        }
    
    }
    

    input.xml/Output

    <?xml version="1.0" encoding="UTF-8"?>
    <A>
       <B>
          <C>
             <D>Foo</D>
             <E>Bar</E>
          </C>
       </B>
    </A>
    

    For More Information