6

我有一个 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>

如何将“描述”更改为“详细信息”?

4

3 回答 3

11

我建议您使用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')
于 2013-04-20T14:28:22.027 回答
0

如果你的 xml 总是这么简单,你可以使用正则表达式:

import re
xml = """
<breakfast_menu>
...
</breakfast_menu>
"""
regex = re.compile('<description>(.*)</description>')
xml = regex.sub(r'<details>\1</details>',xml)
于 2013-04-20T14:34:03.050 回答
-2

那么你有两个选择。如果 xml 很小,则可以使用纯字符串替换。如果 xml 非常大,那么我建议应用 xsl 转换。

于 2013-04-20T14:21:44.837 回答