[英]string parent node xml parse with jaxb java
如何在jaxb中解析具有父节点名称的字符串作为字符串。 我试图通过使用JAXB绑定到模型类来解析我的xml字符串。 我的xml字符串看起来像这样:
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>";
我的问题是我如何创建一个模型类来将这个xml映射到它? 如果我删除字符串父节点,如下所示:
String inputXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ " <Response Code=\"1212\">\n"
+ " <Message>Operation is succesfully completed</Message>\n"
+ " </Response>\n";
我可以创建一个模型类:
@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;
}
}
在我的java类中,我可以使用JAXB解析:
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);
但我必须用xml解析
<string xmlns = \\“ http://tempuri.org/ \\”> ... </ string>
作为父节点。 我甚至尝试过这样的答案: 如何将字符串xml中的字符串xml解析/解组成Java对象?
但没有工作。 我错过了什么吗?
您需要将内容包装在StringReader中,
StringReader reader = new StringReader(inputXml);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) jaxbUnmarshaller.unmarshal(reader);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.