如何使用Python在现有XML中附加一堆标签

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用Python在现有XML中附加一堆标签相关的知识,希望对你有一定的参考价值。

我有一个大的xml文件(2000 kb +),我想用Python附加。我需要检查是否存在具有某些值的标签。如果不是,我需要在特定位置(标签之前)向文件添加一堆标签

让我们举个例子,restaurant.xml:

<restaurant>
    <menu>
        <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>
        </breakfast_menu>
        <lunch_menu>
            blah...blah...blah
    </menu>
</restaurant>

第一步是检查xml文件中是否存在French Toast。如果没有,请在</breakfast_menu>之前添加以下内容

<food>
    <name>French Toast</name>
    <price>$4.50</price>
    <description>Thick slices made from our homemade sourdough bread</description>
    <calories>600</calories>
</food>
答案

尝试下面给出的代码

编辑:

<restaurant>
    <menu>
        <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>
         </breakfast_menu>
    </menu>
</restaurant>

码:

import xml.etree.ElementTree as ET

def SubElementWithText(parent, tag, text):
    attrib = {}
    element = parent.makeelement(tag, attrib)
    parent.append(element)
    element.text = text
    return element

def addXml(file, xpath_to_check, xpath_to_add_element, nodedict):
    tree = ET.parse(file)
    root = tree.getroot()
    if root.findall(xpath_to_check):
        st = False
        for elem in root.findall(xpath_to_check):
            if elem.text == nodedict['name']:
                st = True
        if st == False:
            breakfast_menu = root.find(xpath_to_add_element)
            food = ET.SubElement(breakfast_menu, 'food')
            for element, value  in nodedict.items():
                SubElementWithText(food, element, value)
            tree.write(file)
            print("Elements added successfully")
        else:
            print("ELement already existed")

file = "restaurent.xml"
xpath_to_check = ".//food/name"
xpath_to_add_element = "./menu/breakfast_menu"
nodedict = {"name" : "French Toast", "price" : "$4.50", "description" : "Thick slices made from our homemade sourdough bread" , "calories" : "600" }
addXml(file, xpath_to_check, xpath_to_add_element, nodedict)

以上是关于如何使用Python在现有XML中附加一堆标签的主要内容,如果未能解决你的问题,请参考以下文章

无论如何要在这个python程序中添加一堆csv文件的输入?我想搜索超过 15 个 csv 文件

如何在 python 中读取具有特定标签属性的 xml?

如何在 python 代码中解析多个 xml 文件?

如何在python中根据xml标签获取文本?

如何通过覆盖现有图像将一堆图像转换为黑白图像?

如何通过使用 Python 将标签与字符串匹配来映射 XML 标签?