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 & Pat </firstName>
<sal> < than 10000 </sal>
</personName>
If I am using StringUtils, it converts all the "<" characters like this
<sal> < than 10000 </sal>
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.
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 & Pat
Escaped : > than 10000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With