Monday, May 22, 2023

How to replace escape XML special characters in Java String - Example

When working with XML data in Java, it's important to properly escape special characters to ensure the validity of the XML structure. Here's an example that demonstrates how to replace and escape XML special characters in a Java string:


java

import org.apache.commons.text.StringEscapeUtils;


public class XmlSpecialCharacterExample {

    public static void main(String[] args) {

        String xmlString = "<root><name>John Doe</name><description>Special characters: <>&\"'</description></root>";


        // Escape XML special characters using Apache Commons Text library

        String escapedXml = StringEscapeUtils.escapeXml11(xmlString);


        System.out.println("Original XML: " + xmlString);

        System.out.println("Escaped XML: " + escapedXml);

    }

}

In this example, we're using the StringEscapeUtils.escapeXml11 method from the Apache Commons Text library to escape XML special characters. The method takes a Java string as input and returns a new string with the special characters replaced.


The output of the example will be:

php

Original XML: <root><name>John Doe</name><description>Special characters: <>&"'</description></root>

Escaped XML: &lt;root&gt;&lt;name&gt;John Doe&lt;/name&gt;&lt;description&gt;Special characters: &lt;&gt;&amp;&quot;&apos;&lt;/description&gt;&lt;/root&gt;

As you can see, the XML string containing special characters is properly escaped, and the special characters < > & " ' are replaced with their respective XML entities (&lt; &gt; &amp; &quot; &apos;).


By escaping XML special characters, you can safely include the string within an XML document without causing parsing or structure issues.





No comments:

Post a Comment