对于未来的读者,任何 XML 转换、样式、重新格式化和重新结构都可以使用XSLT(用于 XML 操作的声明性编程语言)充分甚至有效地处理。而 Python 的 lxml 模块维护了一个 XSLT 处理器。
请参阅下面使用 OP 需求的通用示例:
原始 XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>
<entry1>some text</entry1>
<entry2>other text</entry2>
</child>
<child>
<entry1>some text</entry1>
<entry2>other text</entry2>
</child>
</root>
XSLT 脚本
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="root">
<root>
<xsl:for-each select="//child">
<child>
<xsl:copy-of select="entry1"/>
<xsl:if test="entry1='some text'">
<entry2>some new text</entry2>
</xsl:if>
</child>
</xsl:for-each>
</root>
</xsl:template>
</xsl:transform>
Python 脚本
import os
import lxml.etree as ET
cd = os.path.dirname(os.path.abspath(__file__))
dom = ET.parse(os.path.join(cd, 'Original.xml'))
xslt = ET.parse(os.path.join(cd, 'XSLTScript.xsl'))
transform = ET.XSLT(xslt)
newdom = transform(dom)
tree_out = ET.tostring(newdom, encoding='UTF-8', pretty_print=True, xml_declaration=True)
xmlfile = open(os.path.join(cd, 'Final.xml'),'wb')
xmlfile.write(tree_out)
xmlfile.close()
最终的 XML
<?xml version='1.0' encoding='UTF-8'?>
<root>
<child>
<entry1>some text</entry1>
<entry2>some new text</entry2>
</child>
<child>
<entry1>some text</entry1>
<entry2>some new text</entry2>
</child>
</root>
虽然上述内容可能看起来过于复杂,而不是 Python 风格的单行代码,但请注意,在某些情况下,您可能需要进行复杂、错综复杂的 XML 重组,在这种情况下,您可以利用 XSLT 的递归、模板格式化语言,而不是运行复杂的迭代循环面向对象编程(Python、PHP、Java、C# 等)。