Reputation: 154
I have a String in java which is in the XML format. Please note it is not a xml file but a string in XML format.
I need to append a new root element for that.
My xml
<Country>
<Street>ABC</Street>
<City>XYZ</Street>
</Country>
What I need is
<Location>
<Country>
<Street>ABC</Street>
<City>XYZ</Street>
</Country>
</Location>
I tried many ways and also this is related to my problem I posted earlier.
Jaxb Marshals the same XML MessageQuestion
Since I need a quick fix, thought of appending the root somehow.
Thanks in advance.
Upvotes: 0
Views: 428
Reputation: 580
There's probably a more generic and better way of doing what you're trying to do but since the question is about specifically using a String
...
In the comments, you said the indentation matters. That means you need to indent everything you have so far, i.e adding 2 or 4 spaces or a tab or however much you want to indent by. This needs to be done after each \n
character.
You can then put <newRoot>\n
at the start of the string, and \n</newRoot>
at the end of the string.
Note: this will only work "as intended" for already formatted XML input strings. In other words, if you give it
<t1>
<t2>
<t3>
</t3>
</t2>
</t1>
(which is not consistently indented)
It will give you the same inner XML back, but with 1 consistent level of indentation added:
<t0>
<t1>
<t2>
<t3>
</t3>
</t2>
</t1>
</t0>
Upvotes: 1