Escape for XML & JSON

/**
 * @author Jin
 * @version 1.0.0
 */
public class XmlTool {
    public final static String JSONPARSE="forJSONparse";
    public XmlTool() {
        super();
    }
    /**
     * Replace the five special characters by five "predefined entities".
     * The XML specification defines five "predefined entities" representing special characters,
     * and requires that tool honor them.The entities can be explicitly declared in a DTD.
     * The table below lists the five XML predefined entities. The "Name" column mentions the entity's name. The "Character" column shows the character.
     * <p>
     * Name     Character
     * quot     "
     * amp     &
     * apos     '
     * lt     <
     * gt     >
     * </p>
     * @param sChar
     * @return String. The entities was explicitly declared in this string.
     */
   public static String replacePreEntities(String sChar){
        String sR="";
          sR=sChar.trim();
          sR=sR.replaceAll("&","&amp;");
          sR=sR.replaceAll("\"","&quot;");
          sR=sR.replaceAll("\'","&apos;");
          sR=sR.replaceAll("<","&lt;");
          sR=sR.replaceAll(">","&gt;");
        return sR;
        }
  /**
   * escaped double-quote characters, Single quote characters do not need to be escaped.
   *
   * ************************
   * E.g. in the jsp file.
   * **run inside the server
   * <%
   *  String d = "sss'ss\"ssass\"1234zzz";
   *  d=d.replaceAll("\"","\\\\\"");
   *  //d=d.replaceAll("\'","\\\\\'"); //it works.
   *  String testS = "[{\"s\":\""+d+"\"}]";
   * %>
   * **run inside the browser
   * <script type="text/javascript">
   *       var s=<%=testS%>;   //must be this way. Don't use JSON.parse('<%=testS%>'); in Firefox 44.0.2
   *       console.log(s[0].s);
   * </script>
   * ************************
   *@return  String
   * @param String sChar
   * @param String f is null or "forJSONparse".
   * if f is null, this is for var s=<%=testS%>; in javascript.
   * if f is "forJSONparse", this is for JSON.parse('<%=testS%>'); in javascript.
   */
  public static String escapedJSON(String sChar,String f){
       String sR="";
         sR=sChar.trim();
       
         //for var s=<%=testS%>; in javascript.
         if(f==null){
           sR=sR.replaceAll("\"","\\\\\"");//escaped double-quote characters
         }else if(f.equalsIgnoreCase("forJSONparse")){
         //for JSON.parse('<%=testS%>'); in javascript.
           sR=sR.replaceAll("\"","\\\\\\\\\""); //for JSON.parse();
           sR=sR.replaceAll("\'","\\\\\'");//Single quote characters do not need to be escaped,but it works.
           // sR=sR.replaceAll("'","\\\\\'");//single-quotes, it works, too.
         }
       return sR;
       }
   
}

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE