繁体   English   中英

为什么我使用String.replace和HashMap的方法不能替换字符串?

[英]Why is my method using String.replace and a HashMap not replacing the strings?

我试图编写一个小类来转义XML文档中的字符。 我正在使用xpath来获取XML文档的节点,并将每个节点传递给我的类。 但是,它不起作用。 我想改变:

"I would like a burger & fries."

"I would like a burger & fries."

这是我班的代码:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MyReplace{
    private static final HashMap<String,String> xmlCharactersToBeEscaped;
    private Iterator iterator;
    private String newNode;
    private String mapKey;
    private String mapValue;

    static {
        xmlCharactersToBeEscaped = new HashMap<String,String>();
        xmlCharactersToBeEscaped.put("\"","&quot;");
        xmlCharactersToBeEscaped.put("'","&apos;");
        xmlCharactersToBeEscaped.put("<","&lt;");
        xmlCharactersToBeEscaped.put(">","&gt;");
        xmlCharactersToBeEscaped.put("&","&amp;");
    }

    public String replaceSpecialChar(String node){
        if(node != null){
            newNode = node;
            iterator = xmlCharactersToBeEscaped.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry mapEntry = (Map.Entry) iterator.next();
                mapKey = mapEntry.getKey().toString();
                mapValue = mapEntry.getValue().toString();

                if(newNode.contains(mapKey)){
                    newNode = newNode.replace(mapKey,mapValue);
                }
            }
            return newNode;
        } else {
            return node;
        }
    }
}

发生的事情是它将替换地图中的第一个特殊字符,引号,并跳过其他所有内容。

您的解决方案过于复杂。

使用StringEscapeUtils(Common Lang库的一部分)。 它具有内置功能,可以转义和取消转义XML,HTML等。 Commons lang非常易于导入,以下示例来自最新的稳定版本(3.4)。 以前的版本使用不同的方法,请根据您的版本查找Java文档。 它非常灵活,因此您不仅可以使用简单的转义和转义功能,还可以做更多的事情。

String convertedString = StringEscapeUtils.escapeXml11(inputString);

如果您使用的是XML 1.0,它们还提供以下内容

String convertedString10 = StringEscapeUtils.escapeXml10(inputString);

在这里获取: https : //commons.apache.org/proper/commons-lang/

此处的Java文档(3.4): https : //commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/StringEscapeUtils.html

使它更简单(请参阅下面的评论):

xmlCharactersToBeEscaped = new HashMap<String,String>();
xmlCharactersToBeEscaped.put("\"","&quot;");
xmlCharactersToBeEscaped.put("'","&apos;");
xmlCharactersToBeEscaped.put("<","&lt;");
xmlCharactersToBeEscaped.put(">","&gt;");
/* xmlCharactersToBeEscaped.put("&","&amp;"); <-- don't add this to the map */

//...
public String replaceSpecialChars(String node) {
    if (node != null) {
        String newNode = node.replace("&", "&amp;"); 
        for (Map.Entry<String, String> e : xmlCharactersToBeEscaped.entrySet()) {              
             newNode = newNode.replace(e.getKey(), e.getValue());
        }
        return newNode;
    } else {
        return null;
    }
}

或将StringEscapeUtils用于此类内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM