python元素树xml append

2024-05-13 11:47:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在向xml文件添加元素时遇到了一些问题

我有一个具有以下结构的xml:

<Root>
    <Item>
        <ItemId>first</ItemId>
        <Datas>
            <Data>one</Data>
            <Data>two</Data>
            <Data>three</Data>
        </Datas>
    </Item>
    <Item>
        <ItemId>second</ItemId>
        <Datas>
            <Data>one</Data>
            <Data>two</Data>
            <Data>three</Data>
        </Datas>
    </Item>
</Root>

我只想在itemid为second时添加数据,并获得如下输出:

<Root>
    <Item>
        <ItemId>first</ItemId>
        <Datas>
            <Data>one</Data>
            <Data>two</Data>
            <Data>three</Data>
        </Datas>
    </Item>
    <Item>
        <ItemId>second</ItemId>
        <Datas>
            <Data>one</Data>
            <Data>two</Data>
            <Data>three</Data>
            <Data>FOUR</Data>
            <Data>FIVE</Data>
        </Datas>
    </Item>
</Root>

谢谢你的帮助!


Tags: 文件元素datarootxmlitem结构one
2条回答

以下方法可以找到Datas节点并将元素附加到该节点。

from lxml import etree
from xml.etree import ElementTree as ET

xml_str = """<Root>
<Item>
    <ItemId>first</ItemId>
    <Datas>
        <Data>one</Data>
        <Data>two</Data>
        <Data>three</Data>
    </Datas>
</Item>
<Item>
    <ItemId>second</ItemId>
    <Datas>
        <Data>one</Data>
        <Data>two</Data>
        <Data>three</Data>
    </Datas>
</Item>
</Root>"""

# build the tree 
tree = etree.fromstring(xml_str)
# get all items nodes 
items = tree.findall('Item')

for item in items:
    # get ItemId text 
    item_id = item.findtext('ItemId')
    if item_id == 'second':
        # get the Datas node
        datas = item.find('Datas')

        # add an element to it
        new_data = ET.SubElement(datas, 'Data')
        new_data.text = 'New Data'

# print the final xml tree 
print etree.tostring(tree)

目前还不清楚您是希望如何找到添加元素的位置,还是希望如何添加元素本身。

对于这个特定的示例,为了查找位置,您可以尝试以下方法:

import xml.etree.ElementTree as ET
tree=ET.parse('xml-file.txt')
root=tree.getroot()

for item in root.findall('Item'):
    itemid=item.find('ItemId')
    if(itemid.text=='second'):
        #add elements

对于实际的添加部分,您可以尝试:

new=ET.SubElement(item[1],'Data')
new.text='FOUR'
new=ET.SubElement(item[1],'Data')
new.text='FIVE'

或者

new=ET.Element('Data')
new.text='FOUR'
child[1].append(new)
new=ET.Element('Data')
new.text='FIVE'
child[1].append(new)

有其他几种方法可以同时完成这两个部分,但一般来说,文档非常有用:https://docs.python.org/2/library/xml.etree.elementtree.html

编辑:

如果“Datas”元素进一步向下,则可以使用与上面相同的element.find()方法来查找指定标记的第一次出现。(Element.findall()返回指定标记发生的所有事件的列表)。

下面的技巧可以做到:

data=item.find('Datas')
new=ET.SubElement(data,'Data')
new.text='FOUR'
new=ET.SubElement(data,'Data')
new.text='FIVE'

相关问题 更多 >