-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?

4

1 に答える 1

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;
}
于 2012-10-13T06:44:08.130 に答える