23

I am quite sure, this is one of the many duplicated questions around XML to Java Object conversions. But I started this thread since I couldn't find simpler or looking for simpler solution.

I have an xsd [Infact I am designing it] and xml. I would like to auto-map the xml data to Java beans as per mapping

<tns:SummaryCart xmlns:tns="SummaryCart" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="SummaryCart.xsd">
    <SummaryElement type="test">
        <order>1</order>
        <id>A</id>
        <displayName>A</displayName>
        <subElements>
            <order>1</order>
            <id>Preactivation</id>
            <displayName>Preactivation</displayName>
        </subElements>
        <maxlines>1</maxlines>
    </SummaryElement>
</tns:SummaryCart>

Now my Java classes will be

public class SummaryCart{
    private List<SummaryElement> summaryElementList;
}
public class SummaryElement {
    private int order;
    private String id;
    private String displayName;
    private String property;
    private List<SummaryElement> subElements;
    private int maxlines;
    private String type;
}

Is there any simple tool/framework which can auto-map the data from XML to Java beans [MUST support attributes/element mapping]. Tutorial will be good.

Btw, I am using Spring framework, if spring-oxm advantage is taken, its welcome.

RaceBase
  • 18,428
  • 47
  • 141
  • 202

2 Answers2

36

Below is how you could map your object to XML using JAXB (JSR-222). An implementation is included in the JDK/JRE starting with Java SE 6. JAXB is supported by Spring (see section 8.5: http://static.springsource.org/spring-ws/site/reference/html/oxm.html)

SummaryCart

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement(name="SummaryCart", namespace="SummaryCart")
@XmlAccessorType(XmlAccessType.FIELD)
public class SummaryCart{

    @XmlElement(name="SummaryElement")
    private List<SummaryElement> summaryElementList;

}

SummaryElement

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class SummaryElement {

    private int order;
    private String id;
    private String displayName;
    private String property;
    private List<SummaryElement> subElements;
    private int maxlines;

    @XmlAttribute
    private String type;

}

Demo

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

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum15881876/input.xml");
        SummaryCart sc = (SummaryCart) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "SummaryCart.xsd");
        marshaller.marshal(sc, System.out);
    }

}

input.xml/Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SummaryCart xmlns:ns2="SummaryCart" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="SummaryCart.xsd">
    <SummaryElement type="test">
        <order>1</order>
        <id>A</id>
        <displayName>A</displayName>
        <subElements>
            <order>1</order>
            <id>Preactivation</id>
            <displayName>Preactivation</displayName>
            <maxlines>0</maxlines>
        </subElements>
        <maxlines>1</maxlines>
    </SummaryElement>
</ns2:SummaryCart>
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Not to say, we are using JDK 5. Yes, Legacy application. Can i do it with Java 5 by including any of the specific libraries using Maven. – RaceBase Apr 09 '13 at 01:53
  • Here is a pom.xml file that pulls in EclipseLink MOXy as the JAXB impl (I'm the MOXy lead): https://github.com/bdoughan/blog20110819/blob/master/pom.xml – bdoughan Apr 09 '13 at 01:58
  • Note : Use this `@XmlAttribute(name = "type")` on getter instead of property. – Deepesh kumar Gupta Sep 09 '19 at 09:29
  • 1
    Watch out! `JAXBContext.newInstance` should be called once (per type). Otherwise it will lead to memory leak. https://stackoverflow.com/questions/7400422/jaxb-creating-context-and-marshallers-cost – msi Apr 12 '20 at 18:10
1

Basically you want to unmarshal your XML. Here's a detailed tutorial that describes how to use the JAXB xjc command to generate a Java class from XML Schema. A maven xjc plugin is also available for your convenience.

Jops
  • 22,535
  • 13
  • 46
  • 63
  • 1
    You can also use a JAXB implementation when starting from Java classes: http://stackoverflow.com/a/15884122/383861 – bdoughan Apr 08 '13 at 16:20
  • 2
    Noted Blaise. My initial understanding on the OP's question was he wanted to generate Java files out of nothing, using only the XSD as his starting point. Re-reading it again, you're right it seems he just needs a way to map them automatically. Thanks for not down-voting.:) – Jops Apr 08 '13 at 16:30