【问题标题】:string parent node xml parse with jaxb java使用 jaxb java 解析字符串父节点 xml
【发布时间】:2019-06-18 08:28:54
【问题描述】:

如何在 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 进行解析

http://tempuri.org/\">...

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

但不工作。我错过了什么吗?

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      相关资源
      最近更新 更多