How to replace XML special Characters in Java String
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 which provides a function to replace special characters from XML String is Apache commons lang’s StringEscapeUtils class which provide escaping for several languages like XML, SQL, and HTML. you can use StringEscapeUtils to convert XML special character in String to their escaped equivalent. I personally like to use open source code instead of reinventing the wheel to avoid any testing efforts. Even Joshua Bloch as advocated use of Open source library to leverage the experience and work of other programmers. If you are reading from XML file and after doing some transformation writing to another XML file , you need to take care of XML special characters present in the source file. If you don’t escape XML special characters while creating XML document than various XML parsers like DOM and SAX parser will consider those XML meta consider them as XML tag in case of < or >.
