0

How to parse xml having parent node name as string in jaxb. I am trying to parse my xml string by binding into a model class using JAXB. My xml string looks something like this:

String inputXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
            + "<string xmlns=\"http://tempuri.org/\">\n"
            + " <Response Code=\"1212\">\n"
            + "     <Message>Operation is succesfully completed</Message>\n"
            + " </Response>\n"
            + "</string>";

My question is how can I create a model class to map this xml into it? If I remove the string parent node like this:

String inputXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
            + " <Response Code=\"1212\">\n"
            + "     <Message>Operation is succesfully completed</Message>\n"
            + " </Response>\n";

I can create a model class as:

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

String Code;
String Message;
public String getCode() {
    return Code;
}

@XmlAttribute(name = "Code")
public void setCode(String Code) {
    this.Code= Code;
}

public String getMessage() {
    return Message;
}

@XmlElement(name = "Message")
public void setMessage(String Message) {
    this.Message = Message;
}    

@Override
public String toString() {
    return Message;
}
}

And in my java class I can parse using JAXB as:

    InputSource inputSource = new InputSource(new StringReader(inputXml));

    // map xml to model class in jaxb
    JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Response response = (Response) jaxbUnmarshaller.unmarshal(inputSource);

But I have to parse with xml that have

< string xmlns=\"http://tempuri.org/\">...< /string>

as parent node. I even tried to follow this answer: How to parse/unmarshall the string xml inside a string xml into a Java object?

but not working. Am I missing something?

1 Answer 1

0

You need to wrap the content in a StringReader,

StringReader reader = new StringReader(inputXml);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) jaxbUnmarshaller.unmarshal(reader);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.