Rectangle 27 0

java Define XML Structure with Xstream?


<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Version>2.0</Version>
   <Name>John</Name>
   <Age>18</Age>
   <UserId>22491</UserId>
   <Country>USA</Country>
   <AnotherData>
      <Records>
         <AnotherRecord>
            <Field1>XXX</Field1>
            <Field2>XX</Field2>
            <Field3>CCCCCCCC</Field3>
            <Field4>XXX9000</Field4>
            <Field5>XXX00345</Field5>
         </AnotherRecord>
      </Records>
   </AnotherData>
</Root>
@XmlPath("AnotherData/Records/AnotherRecord")
List<AnotherRecord> list;
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
package forum11970410;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11970410/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

Below is what the fully mapped Root class would look like. JAXB does not require any annotations (see: http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html), but since the XML elements in your document do not match the default naming rules some annotations are required.

I do not believe this use case can be handled by XStream. If you are open to using other technologies, below is an example of how it could be done with MOXy. Using the @XmlPath extension.

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

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

You can use the following demo code to prove that everything works:

Note