views:

920

answers:

1

I'm building an XML document and printing out into an indented format using the JVM build-in libraries. When there is a text node in the document that contains a line break, it wraps the line to the start of the line instead of it's proper indented position

sample code

ByteArrayOutputStream s;

s = new ByteArrayOutputStream();

Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Transformer t = TransformerFactory.newInstance().newTransformer();

Element a;
Text b;

a = d.createElement("a");

String text = "multi\nline\ntext";
b = d.createTextNode(text);

a.appendChild(b);
d.appendChild(a);

t.setOutputProperty(OutputKeys.INDENT,"yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(d), new StreamResult(s));

System.out.println(new String(s.toByteArray()));

output

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>multi
line
text</a>

desired output

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
 multi
 line
 text
</a>

Is there a smart way to make each new line begin at where the indented xml tag would begin? Something tells me textnode isn't the right thing to use? Is there something better?

+2  A: 

Note that changing your indentation actually changes the text content of that node. i.e.

<a>
 multi
 line
 text
</a>

will result in multiple leading spaces in your text as read by XML apis. Is that what you want ? I know this isn't an answer to your question, but I'm not sure you really want to maintain indentation. How will you handle text nodes indented further down the XML structure (i.e. with many more leading spaces) ?

Brian Agnew
you're right, i might need to use something like cdata for this
Mike
Or use the encoding allowing it to be put on a single line. Anyway your textnode cannot be pretty printed without altering the contents.
Thorbjørn Ravn Andersen