Search code examples
javaxmljaxbcdata

JAXB unmarshalling CDATA with HTML tags


XML Structure:

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

I can able to parse this XML using JAXB, but the result is crappy, I have used @XmlValue to get the text element value.

Java code:

@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 + "]";
    }
}

Output:

[text= thank you]]]

But I need result like this, eg:

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

or

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

Solution

  • A CDATA section starts with <![CDATA[ and ends with ]]>, so your XML document should become:

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

    Example Code

    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);
        }
    
    }
    

    Output

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

    UPDATE

    thanks, But this case i can't able to edit the XML, bcoz i get XML from third party API. is there any way to get the result, which i except.

    You can use @XmlAnyElement and specify a DomHandler to keep the DOM content as a String. Below is a link to an answer that contains a full example: