Escape XML characters

This example will show escapes the characters in a String using java, guava XmlEscapers and apache commons StringEscapeUtils.escapeXml. If you are looking to escape data within XML, look at using <![CDATA[ your text here ]]>.

Setup

private static final String XML_TO_ESCAPE = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";

private static final String ESCAPED_XML = "&lt;note&gt;&lt;to&gt;Tove&lt;/to&gt;&lt;from&gt;Jani&lt;/from&gt;&lt;heading&gt;Reminder&lt;/heading&gt;&lt;body&gt;Don&apos;t forget me this weekend!&lt;/body&gt;&lt;/note&gt;";

Straight up Java

@Test
public void escape_xml_with_straight_java () {

    StringBuilder escapedXML = new StringBuilder();
    for (int i = 0; i < XML_TO_ESCAPE.length(); i++) {
        char c = XML_TO_ESCAPE.charAt(i);
        switch (c) {
        case '<':
            escapedXML.append("&lt;");
            break;
        case '>':
            escapedXML.append("&gt;");
            break;
        case '\"':
            escapedXML.append("&quot;");
            break;
        case '&':
            escapedXML.append("&amp;");
            break;
        case '
': escapedXML.append("&apos;"); break; default: if (c > 0x7e) { escapedXML.append("&#" + ((int) c) + ";"); } else escapedXML.append(c); } } assertEquals(ESCAPED_XML, escapedXML.toString()); }

Google Guava

Guava XmlEscapers will escaped xml attribute tags value and elements in text or a string.

@Test
public void escape_xml_with_google_guava () {

    String escapedXML = XmlEscapers.xmlAttributeEscaper().escape(XML_TO_ESCAPE);
    assertEquals(ESCAPED_XML, escapedXML);
}

Apache Commons

Apache commons StringEscapeUtils.escapeXml will escape characters in a String using XML entities and supports the five basic XML entities (gt, lt, quot, amp, apos).

@Test
public void escape_xml_with_apache_commons () {

    String escapedXML = StringEscapeUtils.escapeXml(XML_TO_ESCAPE);
    assertEquals(ESCAPED_XML, escapedXML);
}