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
🌐
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.
🌐
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.
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;
}
}
🌐
Blogger
opensourceforgeeks.blogspot.com › 2015 › 03 › escaping-special-characters-of-xml-in.html
Open Source For Geeks: Escaping special characters of XML in Java
For example & character is used to import other XML entities. You can very well write your own piece of code to parse these special characters from the input and replace them with their escaped version. For this tutorial I am going to use Apache commons lang’s StringEscapeUtils class which ...
🌐
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) is preserved in the output, which may result in it being silently converted to "\n" when the XML is parsed. This escaper does not treat surrogate pairs specially and does 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.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Escape special characters
*/ public static String forURL(String aURLFragment){ String result = null; try { result = URLEncoder.encode(aURLFragment, "UTF-8"); } catch (UnsupportedEncodingException ex){ throw new RuntimeException("UTF-8 not supported", ex); } return result; } /** Escape characters for text appearing as XML data, between tags.
🌐
SSOJet
ssojet.com › escaping › xml-escaping-in-java
XML Escaping in Java | Escaping Techniques in Programming
When working with Java data binding ... escaping special characters is often managed automatically during serialization. JAXB, for instance, typically escapes characters such as <, >, &, ', and " by default when marshalling Java objects into XML.
Find elsewhere
🌐
MojoAuth
mojoauth.com › escaping › xml-escaping-in-java
XML Escaping in Java | Escaping Methods in Programming Languages
The most common characters that ... Java can be done using a few simple methods. You can create a utility function that takes a string input and returns the escaped string....
🌐
GeeksforGeeks
origin.geeksforgeeks.org › escaping-xml-special-characters-in-java-string
Escaping XML Special Characters in Java String | GeeksforGeeks
February 22, 2021 - Program to escape XML Special Characters !! Unescaped String: DataStructures & Java Escaped String: DataStructures &amp; Java Unescaped String: DataStructures > Java Escaped String: DataStructures &gt; Java Unescaped String: DataStructures < Java Escaped String: DataStructures &lt; Java Unescaped String: DataStructures " Java Escaped String: DataStructures &quot; Java Unescaped String: DataStructures ' Java Escaped String: DataStructures &apos; Java
🌐
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.
🌐
Dimitris Kolovos
kolovos.wordpress.com › 2014 › 03 › 09 › escaping-xml-special-characters-in-java
Escaping XML special characters in Java – Dimitris Kolovos
March 9, 2014 - If you do not wish to bring in an additional dependency, you can use the following function, which makes use of the built-in W3C XML API, to escape XML special characters in your Java program. public String escapeXml(String target) throws Exception { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Text text = document.createTextNode(target); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(text); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(source, result); return writer.toString(); }
🌐
Stack Overflow
stackoverflow.com › questions › 40017087 › escape-special-character-in-xml
java - escape special character in xml - Stack Overflow
<?xml version="1.0" encoding="UTF-8"?> ... evaluating ClassService.getParameter(\"param1\") ... There not need to escape " characters in XML unless you find them in attributes....
🌐
Coderanch
coderanch.com › t › 553681 › languages › Escape-XML-special-characters
Escape XML special characters? (XML forum at Coderanch)
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. ... Minh Nam wrote: The XML which was output by the Transformer will have the correct escaping already.
🌐
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 - Bizarrely, JAXB will allow you to generate XML even when your input contains control characters. Any control character will hit the default escape mechanism and be converted to its hex representation.
🌐
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
🌐
Mkyong
mkyong.com › home › java › how to escape special characters in java?
How to escape special characters in java? - Mkyong.com
January 20, 2020 - In Java, we can use Apache commons-text to escape the special characters in HTML entities. ... <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.8</version> </dependency> ... package com.mkyong.html; ...