【发布时间】:2012-04-03 02:10:08
【问题描述】:
我想为 Java 类编写一个方法。该方法接受下面给出的 XML 数据字符串作为输入。
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<name> <> Programming in ANSI C <> </name>
<author> <> Balaguruswamy <> </author>
<comment> <> This comment may contain xml entities such as &, < and >. <> </comment>
</book>
<book>
<name> <> A Mathematical Theory of Communication <> </name>
<author> <> Claude E. Shannon <> </author>
<comment> <> This comment also may contain xml entities. <> </comment>
</book>
<!-- This library contains more than ten thousand books. -->
</library>
XML 字符串包含很多以 开头和结尾的子字符串。子字符串可能包含 XML 实体,例如 、、&、' 和 ". 该方法需要将它们替换为 >、<、&。> 和" 分别。
在 Java 中是否有任何正则表达式方法来完成这项任务?
【问题讨论】:
-
您是要转义所有 XML,还是只转义标签之间的 ?
-
谁在生成 XML?似乎解决问题的正确方法是输出有效的 xml,而不是修改内容。
-
子字符串取自数据库。由于 XML 字符串可能包含超过三万个子字符串,因此在添加到 XML 字符串之前转义所有 XML 实体将是低效的。这就是为什么我们只引入 并且该方法负责在使用它之前对 XML 实体进行转义。