Search code examples
javaxmldompretty-printtransformer-model

How to prettify XML String in Java


I have an XML String which is not formatted properly. I would like to do proper indentation using Java. There are a lot of answers on SO regarding this problem. One of the most widely accepted and brilliant answers is this one:

Pretty print XML in java 8

But the problem with this answer is that, the code always needs a root element whereas I have XML tags in my String as follows:

<person>
<address>New York</address>
</person>
<person>
<address>Ottawa</address>
</person>

As you can see there is no root element here. Just multiple tags of person.

I have tried to see any methods available from the libraries used in the above answer. But to no use.

I don't know if there is a way out. But if someone can think of something I would really appreciate it.

P.S. Please please before you mark this as Duplicate, read the question. I know there are similar questions on SO but my problem is quite different.


Solution

  • You can use string manipulation to get close;

    Let's say you have your structure in a string called xml;

    <person>
    <address>New York</address>
    </person>
    <person>
    <address>Ottawa</address>
    </person>
    

    Then add a root element;

    xml = "<myDummyRoot>" + xml + "</myDummyRoot>";
    

    which gives the structure

    <myDummyRoot>
    <person>
    <address>New York</address>
    </person>
    <person>
    <address>Ottawa</address>
    </person>
    </myDummyRoot>
    

    This is a valid XML document that should be possible to intent using the method linked, giving something like;

    <myDummyRoot>
        <person>
            <address>New York</address>
        </person>
        <person>
            <address>Ottawa</address>
        </person>
    </myDummyRoot>
    

    A simple string replaceAll can then remove the root element again

    xml = xml.replaceAll("</?myDummyRoot>", "");
    

    ...which should leave you with a readable XML document (although indented with some extra spacing).