" are illegal when stored in the content, and problems often occur."/> " are illegal when stored in the content, and problems often occur.">

Home  >  Article  >  Backend Development  >  Detailed explanation of the solution when the & < > symbol exists when parsing xml strings

Detailed explanation of the solution when the & < > symbol exists when parsing xml strings

黄舟
黄舟Original
2017-04-01 13:37:302710browse

问题产生:

       在接口调用得出一个xml字符串,一直报错

The entityname must immediately follow the &#39;&&#39; in the entity reference

经查发现  xml的内容里存在有  &符号  而 通过dom4j读取时  会发生错误

在xml中 “&”“140e4624dfe614c0cb4364a4937e6ff2”这样的标签存放在内容里是不合法的,会经常出问题。

下面找到解决方法:实测   替换  &   是可行的。   

public void chartReplace(){
        String str2 = "<logentry revision=&#39;1&#39;>" +
                "<msg>In this comment, I fixed a <bug>, and <added> file1&&file2.</msg>" +
                "</logentry>";
        System.out.println("original string: "+str2);
         
        //替换“&”:$1表示与(<msg>.*)的匹配子序列;$4表示与(.*</msg>)匹配的。
                     //&(?!amp;)表示匹配&而且后面不是amp;的字符串
        //"$1&amp;$3$4"得到的结果就是替换了<msg></msg>中的“&”为“&amp;”
        //由于每次只能替换掉一个“&”,所以循环执行替换,直到替换后与替换前的字符串相等。
        String str1 = "";
        while(!str2.equals(str1)){
            str1 = str2;
            str2 = str1.replaceAll("(<msg>.*)(&(?!amp;))(.*</msg>)", "$1&amp;$3");
        }
        System.out.println("firstly replace \"&\": "+str2);
         
        //替换“<”
        str1 = "";
        while(!str2.equals(str1)){
            str1 = str2;
            str2 = str1.replaceAll("(<msg>.*)(<)(.*</msg>)", "$1&lt;$3");
        }
        System.out.println("then replace \"<\": "+str2);
         
        //替换“<”
        str1 = "";
        while(!str2.equals(str1)){
            str1 = str2;
            str2 = str1.replaceAll("(<msg>.*)(>)(.*</msg>)", "$1&gt;$3");
        }
        System.out.println("finally replace \">\": "+str2);
    }

The above is the detailed content of Detailed explanation of the solution when the & < > symbol exists when parsing xml strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn