擅长:python、mysql、java
<p>使用lxml:</p>
<pre><code>x = """<data>
<name>
<slash>/</slash>
</name>
</data>"""
import lxml.etree as et
xml_doc = et.fromstring(x)
for node in xml_doc.xpath("//*[contains(text(), '/')]"):
node.text = node.text.replace("/","&#x2f;")
print(et.tostring(xml_doc))
</code></pre>
<p>这会给你:</p>
^{pr2}$
<p>或xml:</p>
<pre><code>from xml.etree import ElementTree as et
xml_doc = et.fromstring(x)
for node in xml_doc.iter("*"):
if "/" in node.text:
node.text = node.text.replace("/","&#x2f;")
</code></pre>
<p>要写入文件,<a href="https://stackoverflow.com/questions/38003030/python-how-to-write-empty-tree-node-as-empty-string-to-xml-file/38003299#38003299">this answer</a>同时包含这两个内容。</p>