-1

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?

ycomp
  • 8,316
  • 19
  • 57
  • 95
  • Can you put together an example of your code and perhaps an example of the XML? It's hard to figure out your bug, otherwise. – rolfl Apr 10 '17 at 14:35
  • So you mean none of these should be removing whitespace? I'm not at the computer at the moment... I just thought maybe I was calling the wrong method – ycomp Apr 10 '17 at 14:58

1 Answers1

1

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.

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • I really have no luck, can you think of anything that might cause the line breaks to be removed? they are definitely gone if I use `Element.getValue()` or `.getText()`. I even saved the strings to files to test. Both there and in the debugger, there are no line breaks. My source XML has many line breaks (there is a full page of text in the CDATA section). It uses an Xml Schema, do you think that makes a difference? – ycomp Apr 13 '17 at 02:04
  • oh... I just realized it is a token in my XSD.. that's probably it.. btw - related question - is JDOM2 still under development or at least maintenance? – ycomp Apr 13 '17 at 02:26
  • Yes, JDOM is still active, got 3.5 million downloads per year, going strong. – rolfl Apr 13 '17 at 02:45