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.

XmlEscapeTest.java

package test;

import java.io.File;

import org.apache.commons.io.FileUtils;
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);
		System.out.println(results);

	}

}

Here is the input.txt file:

input.txt

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

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;'.

Results

&lt;sometext&gt;
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.
&lt;/sometext&gt;