python elementtree xml追加

标签 python xml parsing elementtree

我在向 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 为第二个时添加数据,并得到如下输出:

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

感谢您的帮助!

最佳答案

不清楚您是想如何找到添加元素的位置还是如何添加元素本身。

对于这个具体的例子,为了找到哪里,你可以尝试这样的事情:

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'

关于python elementtree xml追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631525/

相关文章:

python - 用于批量电子邮件选择退出的简单 Python 脚本

javascript - 检查xml文件中的元素值

android - 将底部重力设置为单个 View Android

javascript - 将 request.body 解析为字符串然后创建 JSON

python - 如何将 matplotlib 动画转换为 HTML5 <video> 标签

python - 原始 SQL 到 SQLAlchemy

android - 自定义 View 不在 xml 布局 android 中居中

parsing - 有没有办法在宏中实现可选表达式?

python - 在python中解析xml - 不理解DOM

python - 如何在 Pandas 中做 R dplyr?