Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I was surprised to find that StringEscapeUtils in the Apache Commons Lang library doesn't let you specify whether it should double encode existing XML entities or not. After all, even PHP lets you do this. There is a very simple workaround for that however, so read on.

In PHP if you want to avoid double-encoding you simply pass false to the htmlentities() function like so:
 PHP
$strOrig = "&";
$strEnc = htmlentities($strOrig, ENT_XML1, "UTF-8", false);


This will output & instead of & i.e. the string is not double encoded.

To achieve the same result with Java and Apache Commons Lang StringEscapeUtils all you have to do is:
 Java
String strOrig = "&";
String strTemp = StringEscapeUtils.unescapeXml(strOrig);
String strEnc = StringEscapeUtils.escapeXml(strTemp);


That's simple after you see it! Just unescape the string first, then escape it. That will take care of any already encoded entities and will avoid double encoding.



-i

Have comments or feedback on what I wrote? Please share them below! Found this useful? Consider sending me a small tip.
comments powered by Disqus
Other posts you may like...
Hi! You can search my blog here ⤵
Or browse the recent top tags...

Recent Blog Posts

How to fix Google Cloud SDK dev server error - No module named ipaddr

Adorable but totally metal - Metal Earth 3D Guardians of the Galaxy Groot model kit

Riverside Expressway Cam shut down permanently

Inserting Google DFP ads with Backbone, Underscore and jQuery

How to resolve the domain is already mapped to a project error in Google App Engine

A quick look at the Nyko Super MiniBoss wireless controllers for the SNES mini

Loading and displaying a collection from bootstrapped data in Backbone.js

Add this handy function to your Bash profile file to display the compiled JDK version for a .class file

How does PCBWay stack up as a low budget PCB fab

Resolving the Cannot reference X before supertype constructor is called compiler error in Java

Recent Galleries

BMB-012 Nanoblock T-Rex Skeleton Model assembly

Tiny Arcade revision 6 kit assembly and decal application

Atari Lynx repair - Part 5 - McWill LED screen mod installation

Atari Lynx repair - Part 4 - screen cover replacement

Atari Lynx repair - Part 2 - re-capping the motherboard

Atari Lynx repair - Part 3 - broken speaker replacement

Atari Lynx repair - Part 1 - introduction and case disassembly

Building a custom Atari Lynx game box storage shelf unit in a day

Protecting old Atari Lynx game boxes with snug fit plastic sleeves

Monument Valley 2 is released and does not disappoint

Blogs and Friends

Matt Moores Blog
Georgi's FlatPress Guide
Perplexing Permutations
The Security Sleuth
Ilia Rogatchevski
Travelling Fairy

Blog Activity

Blog Activity