You can use apache common text library to escape a string.

org.apache.commons.text.StringEscapeUtils

# For XML 1.0 
String escapedXml = StringEscapeUtils.escapeXml10("the data might contain & or ! or % or ' or # etc");

# For XML 1.1
String escapedXml = StringEscapeUtils.escapeXml11("the data might contain & or ! or % or ' or # etc");

But what you are looking for is a way to convert any string into a valid XML tag name. For ASCII characters, XML tag name must begin with one of _:a-zA-Z and followed by any number of character in _:a-zA-Z0-9.-

I believe there is no library to do this for you so you have to implement your own function to convert from any string to match this pattern or alternatively make it into a value of attritbue.

<property name="no more need to be encoded, it should be handled by XML library">0.0</property>
Answer from gigadot on Stack Overflow
Top answer
1 of 3
56

You can use apache common text library to escape a string.

org.apache.commons.text.StringEscapeUtils

# For XML 1.0 
String escapedXml = StringEscapeUtils.escapeXml10("the data might contain & or ! or % or ' or # etc");

# For XML 1.1
String escapedXml = StringEscapeUtils.escapeXml11("the data might contain & or ! or % or ' or # etc");

But what you are looking for is a way to convert any string into a valid XML tag name. For ASCII characters, XML tag name must begin with one of _:a-zA-Z and followed by any number of character in _:a-zA-Z0-9.-

I believe there is no library to do this for you so you have to implement your own function to convert from any string to match this pattern or alternatively make it into a value of attritbue.

<property name="no more need to be encoded, it should be handled by XML library">0.0</property>
2 of 3
1
public class RssParser {
int length;
    URL url;
URLConnection urlConn;
NodeList nodeList;
Document doc;
Node node;
Element firstEle;
NodeList titleList;
Element ele;
NodeList txtEleList;
String retVal, urlStrToParse, rootNodeName;

public RssParser(String urlStrToParse, String rootNodeName){
    this.urlStrToParse = urlStrToParse;
    this.rootNodeName = rootNodeName;

    url=null;
    urlConn=null;
    nodeList=null;
    doc=null;
    node=null;
    firstEle=null;
    titleList=null;
    ele=null;
    txtEleList=null;
    retVal=null;
            doc = null;
    try {
        url = new URL(this.urlStrToParse);
                    // dis is path of url which v'll parse
        urlConn = url.openConnection();

                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        String s = isToString(urlConn.getInputStream());
        s = s.replace("&", "&amp;");
        StringBuilder sb =
                            new StringBuilder
                                    ("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        sb.append("\n"+s);
        System.out.println("STR: \n"+sb.toString());
        s = sb.toString();

        doc = db.parse(urlConn.getInputStream());
        nodeList = doc.getElementsByTagName(this.rootNodeName); 
        //  dis is d first node which
        //  contains other inner element-nodes
        length =nodeList.getLength();
        firstEle=doc.getDocumentElement();
    }
    catch (ParserConfigurationException pce) {
        System.out.println("Could not Parse XML: " + pce.getMessage());
    }
    catch (SAXException se) {
        System.out.println("Could not Parse XML: " + se.getMessage());
    }
    catch (IOException ioe) {
        System.out.println("Invalid XML: " + ioe.getMessage());
    }
    catch(Exception e){
        System.out.println("Error: "+e.toString());
    }
}


public String isToString(InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[512];
    for (int i; (i = in.read(b)) != -1;) {
        out.append(new String(b, 0, i));
    }
    return out.toString();
}

public String getVal(int i, String param){
    node =nodeList.item(i);
    if(node.getNodeType() == Node.ELEMENT_NODE)
    {
        System.out.println("Param: "+param);
        titleList = firstEle.getElementsByTagName(param);
        if(firstEle.hasAttribute("id"))
        System.out.println("hasAttrib----------------");
        else System.out.println("Has NOTNOT      NOT");
        System.out.println("titleList: "+titleList.toString());
    ele = (Element)titleList.item(i);
    System.out.println("ele: "+ele);
        txtEleList = ele.getChildNodes();
    retVal=(((Node)txtEleList.item(0)).getNodeValue()).toString();
    if (retVal == null)
        return null;
            System.out.println("retVal: "+retVal);
    }
return retVal;
}
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › escaping-xml-special-characters-in-java-string
Escaping XML Special Characters in Java String - GeeksforGeeks
August 21, 2025 - These special characters are also referred to as XML Metacharacters. By the process of escaping, we would be replacing these characters with alternate strings to give the literal result of special characters. To use StringEscapeUtils, add the Apache Commons Text dependency: ... // Java program to escape all the five XML special characters import org.apache.commons.text.StringEscapeUtils; public class GeeksForGeeks { public static void main(String[] args) { System.out.println("Program to escape XML Special Characters !!"); // Escape & character String unescapedXMLString = "DataStructures & Java
🌐
Blogger
javarevisited.blogspot.com › 2012 › 09 › how-to-replace-escape-xml-special-characters-java-string.html
How to replace escape XML special characters in Java String - Example
There are two approaches to replace XML or HTML special characters from Java String, First, Write your own function to replace XML special characters or use any open source library which has already implemented it. Luckily there is one very common open-source library that provides a function to replace special characters from XML String is Apache commons lang’s StringEscapeUtils class which provides escaping for several languages like XML, SQL, and HTML.
🌐
SSOJet
ssojet.com › escaping › xml-escaping-in-java
XML Escaping in Java | Escaping Techniques in Programming
JAXB, for instance, typically escapes characters such as <, >, &, ', and " by default when marshalling Java objects into XML.
🌐
MojoAuth
mojoauth.com › escaping › xml-escaping-in-java
XML Escaping in Java | Escaping Methods in Programming Languages
Use Libraries: Take advantage of existing libraries like Apache Commons Lang or Java's built-in XML libraries to handle escaping, as they often provide optimized and well-tested methods. Consistency: If your application uses XML extensively, establish a consistent approach to escaping across your codebase to avoid errors. Test Thoroughly: Regularly test your XML output to ensure that all special characters are correctly escaped, especially after making changes to your code.
🌐
Guava
guava.dev › releases › 21.0 › api › docs › com › google › common › xml › XmlEscapers.html
XmlEscapers (Guava: Google Core Libraries for Java 21.0 API)
Specifically "\r" (carriage return) ... not perform Unicode validation on its input. ... Returns an Escaper instance that escapes special characters in a string so it can safely be included in XML document as an attribute value....
🌐
Stanford NLP Group
nlp.stanford.edu › nlp › javadoc › javanlp › edu › stanford › nlp › util › XMLUtils.html
XMLUtils (Stanford JavaNLP API)
public static java.lang.String stripTags(java.io.Reader r, java.util.List<java.lang.Integer> mapBack, boolean markLineBreaks) ... mapBack - a List of Integers mapping the positions in the result buffer to positions in the original Reader, will be cleared on receipt ... Reads all text up to next XML tag and returns it as a String. ... Returns a String in which all the XML special characters have been escaped.
🌐
Advanced Installer
advancedinstaller.com › user-guide › xml-escaped-chars.html
XML escaped characters
For example, if you add an existing XML file or create a new one in your project and insert a special XML character in one of its elements, let's say < character, when you will build the project, Advanced Installer will automatically escape this character, replacing it with &lt;. The result is that the XML document installed by the built package will contain the escaped character making possible the correct interpretation of the XML code.
Find elsewhere
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.8.1 › index.html
StringEscapeUtils (Apache Commons Lang 3.8.1 API)
JavaScript is disabled on your browser · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version
🌐
Blogger
opensourceforgeeks.blogspot.com › 2015 › 03 › escaping-special-characters-of-xml-in.html
Open Source For Geeks: Escaping special characters of XML in Java
App Name Before Escaping : Angels & Demons App Name After Escaping : Angels &amp; Demons Angels & Demons · No Exception. I have just shown this demo for '&' special character but you can do the same for all special characters mentioned in "Special Characters in XML" section above. Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than character is legal, but it is a good habit to replace it. Parsing XML files in Java using javax.xml.parsers.DocumentBuilder(OSFG)
🌐
FreeFormatter
freeformatter.com › xml-escape.html
Free Online XML Escape / Unescape Tool - FreeFormatter.com
JavaScript Escape · JSON Escape ... · String Escaper & Utilities · XML Escape - Unescape · Escapes or unescapes an XML file removing traces of offending characters that could be wrongfully interpreted as markup....
🌐
javaspring
javaspring.net › blog › java-utility-to-remove-all-xml-escape-characters-using-java
Java Utility to Remove All XML Escape Characters — javaspring.net
The basic idea behind removing XML escape characters is to replace the escaped sequences (&lt;, &gt;, etc.) with their corresponding original characters (<, >, etc.). We can achieve this by either using regular expressions to match and replace the patterns or by maintaining a mapping of escaped sequences to their original characters and performing a lookup and replacement operation. Regular expressions are a powerful tool in Java for pattern matching and replacement.
🌐
Coderanch
coderanch.com › t › 553681 › languages › Escape-XML-special-characters
Escape XML special characters? (XML forum at Coderanch)
Minh Nam wrote: The XML which was output by the Transformer will have the correct escaping already. Are you asking this question because you actually encountered a problem? The only problem that I can see is that you might have to do Javascript escaping if the source XML contains apostrophes.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Understanding Invalid Characters in XML - Java Code Geeks
May 7, 2024 - An escape sequence is a combination of characters that starts with an ampersand (&), followed by a name or a decimal reference of the character to be escaped, and ends with a semicolon (;). For example, the character “&” itself is an invalid ...
🌐
Stack Exchange
codereview.stackexchange.com › questions › 234915 › escaping-invalid-xml-characters-e-g-for-the-java-dom-api
Escaping invalid XML characters (e.g. for the Java DOM API) - Code Review Stack Exchange
January 1, 2020 - // should not be reviewed String string = "text#text##text#0;text" + '\u0000' + "text<text&text#"; Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = document.createElement("element"); element.appendChild(document.createTextNode(escapeInvalidXmlCharacters(string))); document.appendChild(element); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(new File("test.xml"))); // creates <?xml version="1.0" encoding="UTF-8" standalone="no"?><element>text##text####text##0;text#0;text&lt;text&amp;text##</element> document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("test.xml")); System.out.println(unescapeInvalidXmlCharacters(document.getDocumentElement().getTextContent()).equals(string)); // prints true
🌐
Hedleyproctor
hedleyproctor.com › 2021 › 07 › java-xml-processing-with-jaxb-and-special-characters
Java XML processing with JAXB and special characters | Hedley Proctor
July 27, 2021 - Characters that are permitted, but must either be escaped or inside a CDATA block. Control characters that are not permitted at all. ... If you are creating XML with Java and JAXB, you do not need to do anything to escape these characters, it will be done automatically.
🌐
Experts Exchange
experts-exchange.com › questions › 20758448 › Escape-Characters-in-XML.html
Solved: Escape Characters in XML - Java
October 6, 2003 - >>How can I get all 5 or none of the characters to be escaped? Why does it bother you btw? ... Try getting to them via their ASCII values - 34 for quote, and 39 for single apostrophe. ... >>That's just the way things are done with html AFAIK. Not sure what the connection is with HTML - the output is XML.