【问题标题】:Handling text conversion between java and xml处理java和xml之间的文本转换
【发布时间】:2014-01-13 03:11:34
【问题描述】:

我有一个网络应用程序,允许用户在文本区域中输入文本,然后按保存。

然后将文本以 xml clob 的形式保存到数据库中,并通过 webapp 以 html 的形式显示给用户。

特殊字符存在一些问题。

从文本区保存到xml时,需要对以下字符进行转义: & < > " '

换行符会正确保存到 xml,但是,当它们显示为 html 时,换行符没有任何作用。

这两个问题都可以通过以下方式解决。

保存为 XML 之前:

//get string from text area
string = string.replaceAll("&", "&"); 
string = string.replaceAll("<", "&lt;"); 
string = string.replaceAll(">", "&gt;"); 
string = string.replaceAll("\"", "&quot;");
string = string.replaceAll("\'", "&apos;");

从 xml 中获取文本后:

//get text from xml
string = string.replaceAll("\n", "<br/>"); 

此解决方案适用于我想要实现的目标。

问题是,为了不重新发明轮子或优雅,是否有更好的或现有的解决方案来解决此类问题?

【问题讨论】:

    标签: java xml jsp text escaping


    【解决方案1】:

    你在正确的轨道上。通常,当您创建 JEE Web 应用程序时,您会在名为 ServletUtilities 的类中组合一个处理此类一般转换的类。在其中你可以有一个你可以调用的静态方法,比如“过滤器”,并传递一个字符串参数。所以,你可以有这样的东西:

    public class ServletUtilities
    {
      public static String filter(String input)
      {
         if(!hasSpecialChars(input))
         {
           StringBuffer filtered = new StringBuffer(input.length());
           char c;
           for(int i=0; i < input.length(); i++)
           {
             c = input.charAt(i);
             switch(c)
             {
               case '<' : filtered.append("&lt;");break;
               case '>' : filtered.append("&gt;");break;
               case '"' : filtered.append("&quot;");break;
               case '&' : filtered.append("&amp;");break;
               //This next one is optional for the new line
               case '\n' : filtered.append("<br>");break;
               default: filtered.append(c);
             }
           }
           return(filtered.toString()); 
         }
      }
    
      private static Boolean hasSpecialChars(String input)
      {
        boolean flag = false;
    
        if((input != null) && (input.length() > 0))
        {
           char c;
           for(int i=0; i < input.length(); i++)
           {
             c = input.charAt(i);
             switch(c)
             {
               case '<' : flag = true;break;
               case '>' : flag = true;break;
               case '"' : flag = true;break;
               case '&' : flag = true;break;
               //This next one is optional for the new line
               case '\n' : flag = true;break;
             }
           }
        }
        return flag;
      }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2010-10-10
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      相关资源
      最近更新 更多