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();
}
Advertisements

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s