Skip to content Skip to sidebar Skip to footer

How To Remove The White Spaces Between Tags In Xml

I created an XML document using Java in my android application. I have to call a web service in my application and pass this XML as an argument there. But my problem is there creat

Solution 1:

Of course, it depends on your XML itself. However, you could try using regular expressions.

As an example:

yourXmlAsString.replaceAll(">[\\s\r\n]*<", "><");

Would remove all whitespace between every XML element.

Solution 2:

Method documentBuilderFactory.setIgnoringElementContentWhitespace() controls whitespace creation. Use this before you create a DocumentBuilder.

dbfac.setIgnoringElementContentWhitespace(true);

Solution 3:

I was able to remove whitespace/tabs/newlines from my transformation using the following property:

transformer.setOutputProperty(OutputKeys.INDENT, "no");

You had it set to yes. I'm sure this question is old enough that it doesn't matter now; but if anyone runs into this in the future, setting the property to no saved me.

Solution 4:

This is the regular expression (?:>)(\s*)<

When you use it in the code for Java use "(?:>)(\\s*)<" and replace with "><"

String xmlString = "<note><to>Tove</to><from>Jani</from <heading>Reminder</heading><title>Today</title><body>Don't forget me this weekend!</body></note>";

String str = xmlString.replaceAll("(?:>)(\\s*)<", "><");

This will remove the spaces between the tags and maintain the spaces for the value.

Input:

<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><title>Today</title><body>Don't forget me this weekend!</body></note>

Output:

<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><title>Today</title><body>Don't forget me this weekend!</body></note>

Solution 5:

None of the other answers worked for me. I had to use the below code, to remove both additional whitespaces and new lines.

xmlString.trim().replace("\n", "").replaceAll("( *)<", "<")

Post a Comment for "How To Remove The White Spaces Between Tags In Xml"