jpganz18
jpganz18

Reputation: 5858

any way to convert xml to object in java?

I am trying to use a XML and access to all fields and data on an easy way, so, I decided to use JaxB , but I have no idea how to create all the classes for the objects, I tried manually like this.

@XmlRootElement(name = "Response")
public class Response {

    @XmlElement(ns = "SignatureValue")
    String signatureValue;

}

But I get an error on @XmlElement saying the annotation is disallowed for this location...

I checked other posts and they work great if I have something like Hellw but doesnt work with more complex formats, an example of first part of mine is like this

<?xml version="1.0" encoding="UTF-8"?><DTE xsi:noNamespaceSchemaLocation="http://www.myurl/.xsd" xmlns:gs1="urn:ean.ucc:pay:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

any idea how to do all this??

Thanks in advance

EDIT:

I forgot to say, the XML is actually a String with the entire XML.

Upvotes: 0

Views: 2237

Answers (1)

bdoughan
bdoughan

Reputation: 148977

The @XmlElement annotation is valid on a field. If you have a corresponding property then you should annotate the class with @XmlAccessorType(XmlAccessType.FIELD) to avoid a duplicate mapping exception.

Java Model

Annotating the Field

@XmlRootElement(name = "Response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {

    @XmlElement(name = "SignatureValue")
    String signatureValue;

    public String getSignatureValue() {
        return signatureValue;
    }

    public void setSignatureValue(String signatureValue) {
        this.signatureValue = signatureValue;
    }

}

Annotating the Property

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "Response")
public class Response {

    String signatureValue;

    @XmlElement(name = "SignatureValue")
    public String getSignatureValue() {
        return signatureValue;
    }

    public void setSignatureValue(String signatureValue) {
        this.signatureValue = signatureValue;
    }

}

For More Information

Demo Code

Below is some demo code that reads/writes the XML corresponding to your Response class.

Demo

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

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum19713886/input.xml");
        Response response = (Response) unmarshaller.unmarshal(xml);

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

}

input.xml/Output

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <SignatureValue>Hello World</SignatureValue>
</Response>

Upvotes: 2

Related Questions