如何为XML转义String?

时间:2015-04-14 10:46:58

标签: java fileutils

如何为XML转义字符串?

package test;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;

public class XmlEscapeTest {

    public static void main(String[] args) throws Exception {

        String str = FileUtils.readFileToString(new File("Demo.txt"));
        String results = StringEscapeUtils.escapeXml(str);
        System.out.println(results);

    }

}

Demo.txt 文件包含。

<sometext>
    Here is Demo "Lines" that I'd like to be "escaped" for XML
    & here is some Examples: on Java. Thats?good programming Language.
</sometext>

2 个答案:

答案 0 :(得分:1)

只有五个:

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

他们很容易记住。 HTML有自己的escape codes集合,可以覆盖更多字符。

答案 1 :(得分:1)

您可以使用 CDATA - 阻止

<sometext><![CDATA[
    Here is Demo "Lines" that I'd like to be "escaped" for XML
    & here is some Examples: on Java. Thats?good programming Language.]]>
</sometext>

请在此处查看更多帮助:http://www.w3schools.com/xml/xml_cdata.asp