使用jaxb java解析字符串父节点xml

时间:2019-06-18 08:28:54

标签: java xml jaxb

如何在jaxb中解析以父节点名称作为字符串的xml。我试图通过使用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
  

<字符串xmlns = \“ http://tempuri.org/ \”> ...

作为父节点。我什至尝试遵循以下答案: How to parse/unmarshall the string xml inside a string xml into a Java object?

但不起作用。我想念什么吗?

1 个答案:

答案 0 :(得分:0)

您需要将内容包装在StringReader中,

StringReader reader = new StringReader(inputXml);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) jaxbUnmarshaller.unmarshal(reader);