我有一个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>
如何将“说明”更改为“详细信息”?
答案 0 :(得分:7)
我建议您使用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')
答案 1 :(得分:0)
如果你的xml总是这么简单,你可以使用正则表达式:
import re
xml = """
<breakfast_menu>
...
</breakfast_menu>
"""
regex = re.compile('<description>(.*)</description>')
xml = regex.sub(r'<details>\1</details>',xml)
答案 2 :(得分:-2)
你有两种选择。如果xml很小,那么可以使用普通的字符串替换。如果xml非常大,那么我建议应用xsl转换。