【发布时间】:2019-08-01 04:18:46
【问题描述】:
我需要检查 XML 文件中所有 text() 节点中的所有单词。我使用 XPath //text() 来选择文本节点和一个正则表达式来选择单词。如果该词存在于一组关键字中,我需要将其替换为某些内容并更新 XML。
通常使用.text 设置元素的文本,但_Element 上的.text 只会更改第一个子文本节点。在mixed content element 中,其他文本节点实际上是其前一个兄弟节点的.tail。
如何更新所有文本节点?
在下面的简化示例中,我只是尝试将匹配的关键字包裹在方括号中...
输入 XML
<doc>
<para>I think the only card she has <gotcha>is the</gotcha> Lorem card. We have so many things that we have to do
better... and certainly ipsum is one of them. When other <gotcha>websites</gotcha> give you text, they're not
sending the best. They're not sending you, they're <gotcha>sending words</gotcha> that have lots of problems
and they're <gotcha>bringing</gotcha> those problems with us. They're bringing mistakes. They're bringing
misspellings. They're typists… And some, <gotcha>I assume</gotcha>, are good words.</para>
</doc>
期望的输出
<doc>
<para>I think [the] only card she has <gotcha>[is] [the]</gotcha> Lorem card. We have so many things that we have to do
better... and certainly [ipsum] [is] one of them. When other <gotcha>websites</gotcha> give you text, they're not
sending [the] [best]. They're not sending you, they're <gotcha>sending words</gotcha> that have lots of [problems]
and they're <gotcha>bringing</gotcha> those [problems] with us. They're bringing [mistakes]. They're bringing
misspellings. They're typists… And some, <gotcha>I assume</gotcha>, are good words.</para>
</doc>
【问题讨论】: