我是 python 的新手,我需要修改
<test name="test02"></xmpp> to <test name="test03"></xmpp>
<temp-config>QA</temp-config> to <temp-config>Prod</temp-config>
使用 python 的所有 5 次出现。
不确定要使用什么库。非常感谢这方面的任何帮助。
<config>
<logging></logging>
<test-mode>false</test-mode>
<test name="test02"></xmpp>
<mail></mail>
<test-system>0</test-system>
<system id="0" name="suite1" type="regression">
<temp-config>QA</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="1" name="suite2" type="regression">
<temp-config>QA</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="2" name="suite3" type="regression">
<temp-config>QA</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="3" name="suite4" type="regression">
<temp-config>QA</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="4" name="suite5" type="regression">
<temp-config>QA</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
</config>
使用lxml .此示例使用 lxml.etree
并且实际上会在您的示例 xml 上失败,因为其中有一些未关闭的标记。如果您对要解析的真实数据有同样的问题,请使用可以处理损坏的 xml 的 lxml.html
(作为注释添加到代码中的说明).
In [14]: import lxml.etree as et # for broken xml add an import:
# import lxml.html as lh
In [15]: doc = et.fromstring(xmlstr) # for broken xml replace this line with:
# doc = lh.fromstring(xmlstr)
# if you read xml from a file:
# doc = et.parse('file_path')
In [16]: for elem in doc.xpath('.//temp-config'):
...: elem.text = 'Prod'
...:
In [17]: print et.tostring(doc,pretty_print=True)
<config>
<logging/>
<test-mode>false</test-mode>
<test name="test02">
<mail/>
<test-system>0</test-system>
<system id="0" name="suite1" type="regression">
<temp-config>Prod</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="1" name="suite2" type="regression">
<temp-config>Prod</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="2" name="suite3" type="regression">
<temp-config>Prod</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="3" name="suite4" type="regression">
<temp-config>Prod</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
<system id="4" name="suite5" type="regression">
<temp-config>Prod</temp-config>
<rpm>0.5</rpm>
<cycles>3</cycles>
</system>
</test>
</config>
注意:正如其他人所指出的,您在标准库中有一些不太强大的替代品。对于像这样的简单任务,它们可能非常适合,但是,如果您的 xml 文件已损坏,使用标准库工具解析它们就等于浪费您的时间。