-1

I need to escape the XML string before transform into an XML file. I do it like this:

Java Code :

public static final String[][] XML_ENTITIES = {
    {"&","&amp;"},{">","&gt;"},{"<","&lt;","'","&apos;","\"","&quot;"}
};

public static String escape(String str){
    for(int i=0;i<XML_ENTITIES.length;i++){
        String name = XML_ENTITIES[i][0];
        String value = XML_ENTITIES[i][1];
        int idx = str.indexOf(name);
        if(idx > -1){
            str = str.replace(name, value);
        }
    }
    return str;
}

It works fine but it fails in some cases .

Example :

escape(">>,,a,a<<")

Output:

&gt;&gt;,,a,a&lt;&lt;

Failure Case:

escape("&amp;>,,a,a<<")

Output:

&amp;amp;&gt;,,a,a&lt;&lt;

If a xml string contains &amp; no need to escape the & character in the string . If I unescape the string and do escape it works fine . How can I do without unescaping?

athspk
  • 6,722
  • 7
  • 37
  • 51
kannanrbk
  • 6,964
  • 13
  • 53
  • 94
  • 2
    have you seen `org.apache.commons.lang.StringEscapeUtils.escapeXml()` ? – user1516873 Oct 12 '12 at 07:14
  • @user1516873 this is worth an answer. – David Grant Oct 12 '12 at 07:17
  • Your second example looks correctly escaped to me. If you want to handle partially-escaped strings, consider unescaping the string first, then applying the escape method to the unescaped string. – David Grant Oct 12 '12 at 07:20
  • 3
    A duplicate of [Best way to encode text data for XML in Java](http://stackoverflow.com/questions/439298/best-way-to-encode-text-data-for-xml-in-java) Not to mention reinventing the wheel, nth time. Why do people think that embedding a string containing some special characters is something no one else int the whole universe has done ever before? – ppeterka Oct 12 '12 at 07:45

1 Answers1

0
public static final String[][] XML_ENTITIES = {
    {"&(?!amp;)","&amp;"},{">","&gt;"},{"<","&lt;","'","&apos;","\"","&quot;"}
};

public static String escape(String str){
    for(int i=0;i<XML_ENTITIES.length;i++){
        String name = XML_ENTITIES[i][0];
        String value = XML_ENTITIES[i][1];
        int idx = str.indexOf(name);
        if(idx > -1){
            str = str.replaceAll(name, value);
        }
    }
    return str;
}
mostafa.S
  • 1,452
  • 4
  • 16
  • 27