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 ther
You can create a copy of all nodes in a document, and trims the nodeValue of each node if it exists.
const copyChildrenNodesWithoutWhiteSpace = (document) => {
const clone = document.cloneNode();
for (const child of document.childNodes) {
const childCopy = copyChildrenNodesWithoutWhiteSpace(child);
clone.appendChild(childCopy);
if (childCopy.nodeValue) {
childCopy.nodeValue = childCopy.nodeValue.trim();
}
}
return clone;
};
const result = copyChildrenNodesWithoutWhiteSpace(anyDocument);
This worked for me, thank you. As a caveat, although this is actually useful for my purpose, I noticed that it can also remove text content if that consists only of whitespace. For example, running the following:
String xmlIn = "<tag> </tag> <tag>\t</tag>\t <tag>\r\n</tag><tag> text </tag>";
String xmlOut = xmlIn.replaceAll("(?:>)(\\s*)<", "><");
System.out.println(xmlOut);
gives the following:
<tag></tag><tag></tag><tag></tag><tag> text </tag>
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("( *)<", "<")
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.
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.
Method documentBuilderFactory.setIgnoringElementContentWhitespace() controls whitespace creation. Use this before you create a DocumentBuilder
.
dbfac.setIgnoringElementContentWhitespace(true);