Search code examples
jdom-2

How to get the content of an Element (CDATA) while preserving line breaks?


I tried to get the content of an Element which has only a CDATA section. Inside the CDATA are multiple lines of text.

However when I try element.getValue() .getText() or .getTextTrim() they all strip the line breaks out.

I need to get a String that preserves the linebreaks. What can I do?


Solution

  • Here's some code I put together, based on the example XML file:

    <root>
       <data><![CDATA[This is text
       with some newlines
       in it, and some other spaces.]]></data>
    </root>
    

    and the code:

    public static void main(String[] args) throws JDOMException, IOException {
        Document doc = new SAXBuilder().build("data/cdata.xml");
        String cdata = doc.getRootElement().getChild("data").getText();
        System.out.println(cdata);
    }
    

    which produces the output:

    This is text
       with some newlines
       in it, and some other spaces.
    

    which implies that it works OK.