Skip to content
Advertisement

Adding linebreak in xml file before root node

I am trying to add line break after my comments above the root node in XML document.

I need something like this:

JavaScript

But What I was able to get is this(Line break inside the root but I need line break after the comment):

JavaScript

I need to add the line break just after my comment. Is there a way to do this?

My code:

JavaScript

Advertisement

Answer

You basically want a text node containing a line break after the comment node.

JavaScript


EDIT: It seems that appending even whitespace-only text nodes is not allowed at the root node of an org.w3c.dom.Document. This is 100% formally correct, but also unhelpful.

The way comments are rendered in the output of the Transformer is determined by the serializer it uses (there are different serializers for HTML, XML and plain text outputs). In the built-in XML serializer the end of a comment is defined as --> – without a newline.

Since the internals of javax.xml.transform.Transformer are hard-wired, the serializers are not public API and the class is marked as final, overriding that behavior or setting a custom serializer is impossible.

In other words, you are out of luck adding your line break in a clean way.

You can, however, safely add it in a slightly unclean way:

JavaScript

Doing search-and-replace operations on XML strings is highly discouraged in general, but in this case there is little that can go wrong.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement