简体   繁体   English

用于重命名XML元素的Python

[英]Python for renaming XML elements

I have a XML file where I want to edit or rename elements and save the file. 我有一个XML文件,我想在其中编辑或重命名元素并保存文件。 What is the best way to do it. 最好的方法是什么。 The XML file is given below 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>

How can I change "description" to "details"? 如何将“描述”更改为“详细信息”?

I'm suggesting you to use ElementTree to parse your XML document. 我建议您使用ElementTree来解析XML文档。

This is the simple and the best library to deal with XML docs in python. 这是处理python中的XML文档的最简单,最好的库。

Here is an example code: 这是一个示例代码:

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')

If your xml will always stay this simple, you could use regular expressions: 如果您的xml始终保持这种简单,则可以使用正则表达式:

import re
xml = """
<breakfast_menu>
...
</breakfast_menu>
"""
regex = re.compile('<description>(.*)</description>')
xml = regex.sub(r'<details>\1</details>',xml)

Well you have two options. 好吧,您有两个选择。 If the xml is small, a plain string replacement would do. 如果xml小,则可以使用纯字符串替换。 If the xml is very big then I would advise applying a xsl transformation. 如果xml非常大,那么我建议您应用xsl转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM