JAXB使用HTML标记解组CDATA

时间:2013-05-22 05:23:15

标签: java xml jaxb cdata

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

1 个答案:

答案 0 :(得分: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,bcoz我得到了XML   来自第三方API。有没有办法得到结果,我   除。

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