你能给我一些关于如何使用 python 修改 XML 中的元素文本的建议吗? 如果我想在第一个 BBB 元素的文本前面插入其他文本,我应该在下面的代码中更改哪一部分?
请不要使用 fromstring 和其他模块(例如 lxml)。
这是下面的示例 XML。
<?xml version="1.0"?>
<data>
<AAA>
<CCC>
<BBB>This</BBB> ----> the first BBB element
</CCC>
<CCC>
<BBB>is</BBB>
</CCC>
<CCC>
<BBB>test1</BBB>
</CCC>
</AAA>
<AAA>
<CCC>
<BBB>This is test</BBB>
</CCC>
</AAA>
</data>
这是我在下面尝试的代码。
import xml.etree.ElementTree as ET
import re
tree = ET.parse("C:\\test\\python test\\data_text.xml")
root = tree.getroot()
for AAA in root.findall('AAA'):
for CCC in AAA.findall('CCC'):
for BBB in CCC.findall('BBB')[0]:
BBB_text = '11111' + BBB.text
print(BBB_text)
tree.write('C:\\test\\python test\\output.xml')
据我所知,对于 CCC.findall('BBB')[0] 中的 BBB:
[0]表示只找到第一个BBB,但我猜是错误的。
这就是我想要的结果。
<?xml version="1.0"?>
<data>
<AAA>
<CCC>
<BBB>11111This</BBB> ----> the first BBB element
</CCC>
<CCC>
<BBB>is</BBB>
</CCC>
<CCC>
<BBB>test1</BBB>
</CCC>
</AAA>
<AAA>
<CCC>
<BBB>This is test</BBB>
</CCC>
</AAA>
</data>
请您参考如下方法:
如果您只需要更新单个标签,则无需遍历所有标签。
尝试:
import xml.etree.ElementTree as ET
tree = ET.parse(filename)
root = tree.getroot()
for AAA in root.findall('AAA'):
if AAA.find('CCC'):
BBB = AAA.find('CCC').find('BBB')
BBB.text = '33333' + BBB.text
tree.write('C:\\test\\python test\\output.xml')
