This question is regarding pretty-printing with Java and XML. The data itself is stored in XML but I am using Java to manipulate the data. I have the following code
<ParentElement>
<ChildElement><HeaderNum>34</HeaderNum><LineNum>21</LineNum></ChildElement>
<ChildElement><HeaderNum>42</HeaderNum><LineNum>54</LineNum></ChildElement>
</ParentElement>
I want to insert another ChildElement in between the two existing ChildElement lines. I have no problem actually doing this, but I need to maintain that formatting. If I use
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
It will completely reformat the file. If I set that property to "no", it inserts the new , but not on its own line. It comes on the same line as the first .
Personally I'd just make both of these values attributes, but I can't change the formatting of the file. Is there a way to insert a new on its own line, but without any other formatting?
If you aren't willing/able to trust the serializer's indentation -- and sometimes you can't, because the whitespace is actually part of the XML document's content -- then you're going to have to manage the whitespace yourself by inserting an appropriate text node in front oe new element.
The DOM doesn't have anything built-in to assist you with that, since the DOM doesn't know what text is or isn't meaningful and doesn't know what indentation conventions you're using.