1

XML结构:

<rep>
<text type="full">[!CDATA[Demo, <a href="http://www.google.com" target="_blank">Search</a> thank you]]</text>
</rep>

我可以使用 JAXB 解析这个 XML,但结果很糟糕,我曾经用来@XmlValue获取文本元素值。

Java代码:

@XmlRootElement(name = "rep")
public class Demo {
    @XmlElement(name = "text")
    private Text text;

    @Override
    public String toString() {
        return text.toString();
    }
}
@XmlRootElement(name = "text")
public class Text {
    @XmlValue
    private String text;

    @Override
    public String toString() {
        return "[text=" + text + "]";
    }
}

输出:

[text= thank you]]]

但我需要这样的结果,例如:

[!CDATA[Demo, <a href="http://www.google.com" target="_blank">Search</a> thank you]]

或者

Demo, <a href="http://www.google.com" target="_blank">Search</a> thank you
4

1 回答 1

0

CDATA 部分以 开头<![CDATA[和结尾]]>,因此您的 XML 文档应变为:

<rep>
<text type="full"><![CDATA[Demo, <a href="http://www.google.com" target="_blank">Search</a> thank you]]></text>
</rep>

示例代码

import java.io.File;
import javax.xml.bind.*;

public class Example {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Demo.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xsr = new File("src/forum16684040/input.xml");
        Demo demo = (Demo) unmarshaller.unmarshal(xsr);

        System.out.println(demo);
    }

}

输出

[text=Demo, <a href="http://www.google.com" target="_blank">Search</a> thank you]

更新

谢谢,但是这种情况下我无法编辑 XML,因为我从第三方 API 获取 XML。有什么方法可以得到结果,我除外。

您可以使用@XmlAnyElement并指定 aDomHandler以将 DOM 内容保留为String. 以下是包含完整示例的答案的链接:

于 2013-05-22T10:03:25.970 回答