用Python重命名XML元素

7

我有一个XML文件,想要编辑或重命名元素并保存文件。最好的方法是什么?下面是给出的XML文件。

<breakfast_menu>
<food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
    <calories>650</calories>
</food>
<food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>light Belgian waffles covered with strawberries and whipped cream</description>
    <calories>900</calories>
</food>
<food>
    <name>Berry-Berry Belgian Waffles</name>
    <price>$8.95</price>
    <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
    <calories>900</calories>
</food>
<food>
    <name>French Toast</name>
    <price>$4.50</price>
    <description>thick slices made from our homemade sourdough bread</description>
    <calories>600</calories>
</food>
<food>
    <name>Homestyle Breakfast</name>
    <price>$6.95</price>
    <description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
    <calories>950</calories>
</food>
</breakfast_menu>

如何将“description”更改为“details”?
3个回答

13

我建议您使用ElementTree来解析您的XML文档。

这是在Python中处理XML文档的最简单和最好的库。

以下是示例代码:

import xml.etree.ElementTree as xmlParser
xmlDoc = xmlParser.parse('path to your xml doc')
rootElement = xmlDoc.getroot()

for element in rootElement.iter('description'):
    element.tag = 'details'

# Saving the xml
xmlDoc.write('path to your new xml doc')

如何修复格式不正确的 XML,其中开放标签和关闭标签不匹配。就像下面的 XML 一样。 - user1138880

0
如果你的 XML 结构始终如此简单,你可以使用正则表达式:
import re
xml = """
<breakfast_menu>
...
</breakfast_menu>
"""
regex = re.compile('<description>(.*)</description>')
xml = regex.sub(r'<details>\1</details>',xml)

如何修复格式不正确的XML,其中开放标签和关闭标签不匹配。 - user1138880
你可以将正则表达式分解为开放和关闭标签两个部分:opening = re.compile('<description>') closing = re.compile('</description>')。这将替换开放标签,即使没有关闭标签,但是格式不正确的XML将不会自动修复。 通常使用正则表达式处理非规则标记不是一个好主意。但是,如果您完全确定输入始终遵循某些规则,则正则表达式非常好且非常有效。 - Jen-Ya

-2

你有两个选项。如果 xml 文件很小,可以使用普通的字符串替换方法。如果 xml 文件非常大,建议使用 xsl 转换。


这只是一个更长文件的一部分。我如何使用Python进行XSL转换? - user1138880

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接