Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Escape Characters in Java

Tags:

java

xml

I have an object which I write to an xml. The xml has escape characters like "&", "<" etc. Now before I process this xml I want a utility to escape these special characters so that the resultant xml has & followed by "amp;" for "&" and "&" followed by "lt;" for "<". I tried StringUtils, XMLWriter and few more but they convert the "<" in opening and closing tags as well which I dont want. I only want "<" in the attribute values to be replaced. Please help. Example;

I have the input xml as this

<?xml version="1.0" encoding="UTF-8"?>
<personName><firstName>Sam & Pat </firstName>
<sal> > than 10000 </sal>
</personName>

And the expected xml should be `

<?xml version="1.0" encoding="UTF-8"?>
<personName><firstName>Sam &amp; Pat </firstName>
<sal> &lt; than 10000 </sal>
</personName>

If I am using StringUtils, it converts all the "<" characters like this

&lt;sal&gt; &lt; than 10000 &lt;/sal&gt;

EDIT: I can't actually use JaxB. I am using FreeMarkerTemplate to do this. Here is the code .

File tempFile = File.createTempFile(fileName, ".tmp");
try (FileWriter writer = new FileWriter(tempFile)) {
freeMarkerConfig.setOutputEncoding(UTF_8);
    Template template = freeMarkerConfig.getTemplate(templateName);
    template.process(data, writer);
}              `                                                                                                    
The resultant file which get created should have the handled escape characters.
like image 982
user2111569 Avatar asked Oct 21 '25 17:10

user2111569


1 Answers

You can also use Apache Commons Lang Library for escaping the characters:

Example:

    String escapeString1 = "Sam & Pat ";
    System.out.println("Escaped : " + StringEscapeUtils.escapeXml11(escapeString1));

    String escapeString2 = " > than 10000";
    System.out.println("Escaped : " + StringEscapeUtils.escapeXml11(escapeString2));

Output:

Escaped : Sam &amp; Pat 
Escaped :  &gt; than 10000
like image 76
Flagman Avatar answered Oct 23 '25 07:10

Flagman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!