ghTvNath
ghTvNath

Reputation: 357

Convert xml string to Java object

I have the following xml string. I want to convert it in to a java object, to map each tag with the fields of that object. Its better that if I can introduce different field names compared to tag name. How I can do that? I am looking on JAXB but I am still confused about parts like "ns4:response" and tags within tags. Thank you in advance...

<ns4:response>
    <count>1</count>
    <limit>1</limit>
    <offset>1</offset>
    <ns3:payload xsi:type="productsPayload">
        <products>
            <product>
                <avgRating xsi:nil="true"/>
                <brand>Candie's</brand>
                <description>
                    <longDescription>
                    long descriptions
                    </longDescription>
                    <shortDescription>
                    short description
                    </shortDescription>
                </description>
                <images>
                    <image>
                        <altText>alternate text</altText>
                        <height>180.0</height>
                        <url>
                        url
                        </url>
                        <width>180.0</width>
                    </image>
                </images>
                <price>
                    <clearancePrice xsi:nil="true"/>
                    <regularPrice xsi:nil="true"/>
                    <salePrice>28.0</salePrice>
                </price>
            </product>
        </products>
    </ns3:payload>
</ns4:response>

Upvotes: 9

Views: 81957

Answers (4)

bdoughan
bdoughan

Reputation: 148977

JAXB is the Java standard (JSR-222) for converting objects to/from XML. The following should help:

Unmarshalling from a String

You will need to wrap the String in an instance of StringReader before your JAXB impl can unmarshal it.

StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(sr);

Different Field and XML Names

You can use the @XmlElement annotation to specify what you want the name of the element to be. By default JAXB looks at properties. If you wish to base the mappings on the fields then you need to set @XmlAccessorType(XmlAccessType.FIELD).

@XmlElement(name="count")
private int size;

Namespaces

The @XmlRootElement and @XmlElement annotations also allow you to specify namespace qualification where needed.

@XmlRootElement(namespace="http://www.example.com")
public class Response {
}

For More Information

Upvotes: 32

Miguel Zapata
Miguel Zapata

Reputation: 119

If you already have the xml, and comes more than one attribute, you can handle it as follows:

    String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
    <nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
    <nomCiudad>Pereira</nomCiudad></ciudads>";
    DocumentBuilder db = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(output));

    Document doc = db.parse(is);
    NodeList nodes = ((org.w3c.dom.Document) doc)
        .getElementsByTagName("ciudad");

    for (int i = 0; i < nodes.getLength(); i++) {           
        Ciudad ciudad = new Ciudad();
        Element element = (Element) nodes.item(i);

        NodeList name = element.getElementsByTagName("idCiudad");
        Element element2 = (Element) name.item(0);
        ciudad.setIdCiudad(Integer
            .valueOf(getCharacterDataFromElement(element2)));

        NodeList title = element.getElementsByTagName("nomCiudad");
        element2 = (Element) title.item(0);
        ciudad.setNombre(getCharacterDataFromElement(element2));

        ciudades.getPartnerAccount().add(ciudad);
    }
    }

    for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
    System.out.println(ciudad1.getIdCiudad());
    System.out.println(ciudad1.getNombre());
    }

the method getCharacterDataFromElement is

    public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
    CharacterData cd = (CharacterData) child;

    return cd.getData();
    }
    return "";
    }

Upvotes: 2

Piotr Gwiazda
Piotr Gwiazda

Reputation: 12212

JAXB is a good shot. If you have a XSD file for this document this will be very easy. JAXB can generate Java code for specidied schema. If you do not have an XSD file you'll need to prepare Java classes on your own. Look for JAXB tutorial and check documentation http://jaxb.java.net/tutorial/. Tags within tags are just nested objects for JAXB. ns4 is a namespace. JAXB supports namespaces - just look it up in documentation. You can use annotations to introduce different field names than tags in XML. Follwo the documentation.

Upvotes: 2

NiranjanBhat
NiranjanBhat

Reputation: 1832

Incase you have the XSD for the above shown XML.
I would recommend you to use Jaxb.
JAXB creates java objects from XML files. You will need to first generate Java classes using jaxb's code generator which takes XSD as the input and then serialize/deserialize these xml files appropriately.

Upvotes: 1

Related Questions