Siddharth Trikha Siddharth Trikha - 2 months ago 8
Java Question

Remove empty elements xml string java?

I have an xml string from which I want to remove the empty elements and the line containing the element.

So fir example:

XML:

<ct>
<c>http://192.168.105.213</c>
<l>http://192.168.105.213</l>
<o></o>
<l>http://192.168.105.213</l>
<o>http://192.168.105.213</o>
<ct>


In this
<o></o>
is the empty element, so after removing this element I want :

<ct>
<c>http://192.168.105.213</c>
<l>http://192.168.105.213</l>
<l>http://192.168.105.213</l>
<o>http://192.168.105.213</o>
<ct>


So the whole line must be removed such that it is indented back.

I tried:
xml.replaceAll("<(\\w+)></\\1>", ""));


This leaves an empty line in between:

<ct>
<c>http://192.168.105.213</c>
<l>http://192.168.105.213</l>

<l>http://192.168.105.213</l>
<o>http://192.168.105.213</o>
</ct>


How to remove the space or
\n, \t, \r
correctly to get the proper indentation ?

Answer

This would work:

xml.replaceAll("<(\\w+)></\\1>\n\\s+", ""));

It would match a new line followed by one or more empty spaces (including tabs), which is preceded by your pattern.