简体   繁体   English

字符串父节点xml与jaxb java解析

[英]string parent node xml parse with jaxb java

How to parse xml having parent node name as string in jaxb. 如何在jaxb中解析具有父节点名称的字符串作为字符串。 I am trying to parse my xml string by binding into a model class using JAXB. 我试图通过使用JAXB绑定到模型类来解析我的xml字符串。 My xml string looks something like this: 我的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>";

My question is how can I create a model class to map this xml into it? 我的问题是我如何创建一个模型类来将这个xml映射到它? 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: 在我的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);

But I have to parse with xml that have 但我必须用xml解析

< string xmlns=\\" http://tempuri.org/ \\">...< /string> <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? 我甚至尝试过这样的答案: 如何将字符串xml中的字符串xml解析/解组成Java对象?

but not working. 但没有工作。 Am I missing something? 我错过了什么吗?

You need to wrap the content in a StringReader, 您需要将内容包装在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM