I would like to replace text in an XML file, but preserve any other formatting in the source file.
E.g. parsing it as DOM, replacing the node using XPath and output as String might not do the trick as it will reformat the entire file. (pretty printing might be good for 99% of the cases, but the requirement is to preserve existing formatting, even if it's not "pretty")
Is there any Java / Scala library that can do a "find and replace" on a String, without parsing it as a DOM tree? or at least be able to preserve the original formatting?
EDIT:
I think that the maven replacer plugin does something like this, it seems that it preserves original whitespace formatting by using setPreserveSpace
(I think, need to try)
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
...
private String writeXml(Document doc) throws Exception {
OutputFormat of = new OutputFormat(doc);
of.setPreserveSpace(true);
of.setEncoding(doc.getXmlEncoding());
StringWriter sw = new StringWriter();
XMLSerializer serializer = new XMLSerializer(sw, of);
serializer.serialize(doc);
return sw.toString();
}
So the question changes to: Is there a (straight forward) way to do so without extra dependencies?
EDIT2:
The requirement is to use an XPath query provided externally, i.e. as a String.