簡體   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