Escaping XML special characters in Java

If you do not wish to bring in an additional dependency, you can use the following function, which makes use of the built-in W3C XML API, to escape XML special characters in your Java program.

public String escapeXml(String target) throws Exception {
	Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
	Text text = document.createTextNode(target);
	Transformer transformer = TransformerFactory.newInstance().newTransformer();
	DOMSource source = new DOMSource(text);
	StringWriter writer = new StringWriter();
	StreamResult result = new StreamResult(writer);
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	transformer.transform(source, result);
	return writer.toString();
}

3 thoughts on “Escaping XML special characters in Java

  1. Wooh! I finally found this pure DOM-based example (on third page of Google search results!) I can’t believe that even today most of the the Internet suggests using apache-commons library or even worse – do it manually. Thanks Dmitris a lot for your code, you saved me some time.

Leave a reply to Igor Kolomiets Cancel reply