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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.