2013-05-22 41 views
1

XML结构:JAXB解组CDATA HTML标记

<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 

回答

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] 

UPDATE

感谢,但这种情况下,我能不能够编辑XML,bcoz我从第三方API XML 。有没有什么办法可以得到结果,除了我以外。

您可以使用@XmlAnyElement并指定DomHandle R键保持DOM内容为String。下面是一个答案的链接,其中包含一个完整的例子:

+0

感谢,但这种情况下,我能不能够编辑XML,bcoz我从第三方API XML。有什么方法可以得到结果,除了我之外。 – RAjKuamr

+0

@RAjKuamr - 我根据您的评论更新了我的答案。 –