How do I escape a String for XML?
Author: Deron Eriksson
Description: This Java example shows how to escape a String for XML using StringEscapeUtils.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

XMLW has five basic entities: gt, lt, quot, amp, and apos. The escapeXml() method of the StringEscapeUtils class of the Commons LangS library can be used to escape a String with these entities. The XmlEscapeTest class demonstrates this. It reads a String of text from the input.txt file and XML escapes the String. It displays the results to the console.

package test;


import org.apache.commons.lang.StringEscapeUtils;

public class XmlEscapeTest {

	public static void main(String[] args) throws Exception {

		String str = FileUtils.readFileToString(new File("input.txt"));
		String results = StringEscapeUtils.escapeXml(str);



Here is the input.txt file:


Here is some "Text" that I'd like to be "escaped" for XML
& here is some Swedish: Tack. Vars?god.

The results are shown below. Notice that the XML entities have been substituted in the String at the correct places. Also notice that the Swedish 'å' character has been replaced by its numerical equivalent, '&#229;'.


Here is some &quot;Text&quot; that I&apos;d like to be &quot;escaped&quot; for XML
&amp; here is some Swedish: Tack. Vars&#229;god.