简体   繁体   English

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

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

I am attempting to write a little class to escape characters in an XML document. 我试图编写一个小类来转义XML文档中的字符。 I am using xpath to get the nodes of the XML document, and passing each node to my class. 我正在使用xpath来获取XML文档的节点,并将每个节点传递给我的类。 However, it is not working. 但是,它不起作用。 I want to change: 我想改变:

"I would like a burger & fries."

to

"I would like a burger & fries."

Here is the code for my class: 这是我班的代码:

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;
        }
    }
}

What is happening is that it is replacing the first special character in the map, the quote, and skipping everything else. 发生的事情是它将替换地图中的第一个特殊字符,引号,并跳过其他所有内容。

Your solution is over complicated. 您的解决方案过于复杂。

Use StringEscapeUtils (Part of the Commons Lang library). 使用StringEscapeUtils(Common Lang库的一部分)。 This has a built in feature to escape and unescape XML, HTML and much more. 它具有内置功能,可以转义和取消转义XML,HTML等。 Commons lang is very easy to import and the following examples are from the latest stable release (3.4). Commons lang非常易于导入,以下示例来自最新的稳定版本(3.4)。 Previous versions use different methods, look up the Java doc dependant on your version. 以前的版本使用不同的方法,请根据您的版本查找Java文档。 It's very flexible so you can do a lot more with it than just simple escapes and unescapes. 它非常灵活,因此您不仅可以使用简单的转义和转义功能,还可以做更多的事情。

String convertedString = StringEscapeUtils.escapeXml11(inputString);

If you're using XML 1.0 they also offer the following 如果您使用的是XML 1.0,它们还提供以下内容

String convertedString10 = StringEscapeUtils.escapeXml10(inputString);

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

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

Make it simpler (and see comment below): 使它更简单(请参阅下面的评论):

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;
    }
}

or better use StringEscapeUtils for such stuff. 或将StringEscapeUtils用于此类内容。

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

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