我有一个 XML 数据字符串。我需要转义节点内的值,而不是节点本身。
Ex:
<node1>R&R</node1>
应该转义到:
<node1>R&R</node1>
不应该逃逸到:
<node1>R&R</node1>
过去几天我一直在努力解决这个问题,但并没有取得多大成功。我不是 Java 专家,但以下是我尝试过但不起作用的方法:
- 将字符串 xml 解析到文档中。不起作用,因为节点内的数据包含无效的 xml 数据。
- 逃离所有角色。不起作用,因为接收该数据的程序不会接受这种格式的数据。
- 转义所有字符然后解析到文档中。抛出各种错误。
任何帮助将非常感激。
您可以使用正则表达式匹配来查找尖括号之间的所有字符串,并循环/处理每个字符串。在这个例子中我使用了阿帕奇公共语言进行 XML 转义。
public String sanitiseXml(String xml)
{
// Match the pattern <something>text</something>
Pattern xmlCleanerPattern = Pattern.compile("(<[^/<>]*>)([^<>]*)(</[^<>]*>)");
StringBuilder xmlStringBuilder = new StringBuilder();
Matcher matcher = xmlCleanerPattern.matcher(xml);
int lastEnd = 0;
while (matcher.find())
{
// Include any non-matching text between this result and the previous result
if (matcher.start() > lastEnd) {
xmlStringBuilder.append(xml.substring(lastEnd, matcher.start()));
}
lastEnd = matcher.end();
// Sanitise the characters inside the tags and append the sanitised version
String cleanText = StringEscapeUtils.escapeXml10(matcher.group(2));
xmlStringBuilder.append(matcher.group(1)).append(cleanText).append(matcher.group(3));
}
// Include any leftover text after the last result
xmlStringBuilder.append(xml.substring(lastEnd));
return xmlStringBuilder.toString();
}
这会查找 text 的匹配项,捕获标签名称和包含的文本,清理包含的文本,然后将其放回一起。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)