Python Lxml-使用新数据附加现有的xml [英] Python Lxml - Append a existing xml with new data

查看:76
本文介绍了Python Lxml-使用新数据附加现有的xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python/lxml的新手,在阅读lxml站点并深入研究python之后,我找不到解决n00b麻烦的方法.我有以下xml示例:

I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample:

---------------
<addressbook>
    <person>
        <name>Eric Idle</name>
        <phone type='fix'>999-999-999</phone>
        <phone type='mobile'>555-555-555</phone>
        <address>
            <street>12, spam road</street>
            <city>London</city>
            <zip>H4B 1X3</zip>
        </address>
    </person>
</addressbook>
-------------------------------

我试图将一个孩子附加到根元素,然后将整个文件写回为新的xml或覆盖现有的xml.目前我只写一行.

I am trying to append one child to the root element and write the entire file back out as a new xml or over write the existing xml. Currently all I am writing is one line.

from lxml import etree
tree = etree.parse('addressbook.xml')
root = tree.getroot()
oSetroot = etree.Element(root.tag)
NewSub = etree.SubElement ( oSetroot, 'CREATE_NEW_SUB' )
doc = etree.ElementTree (oSetroot)
doc.write ( 'addressbook1.xml' )

TIA

推荐答案

可以通过复制旧树的全部(而不仅仅是根树)来制作一棵新树标记!-),但是就地编辑现有的树要简单得多(为什么不呢?-)...:

You could make a new tree by copying over all of the old one (not just the root tag!-), but it's much simpler to edit the existing tree in-place (and, why not?-)...:

tree = etree.parse('addressbook.xml')
root = tree.getroot()
NewSub = etree.SubElement ( root, 'CREATE_NEW_SUB' )
tree.write ( 'addressbook1.xml' )

放置在addressbook1.xml中的

<addressbook>
    <person>
        <name>Eric Idle</name>
        <phone type="fix">999-999-999</phone>
        <phone type="mobile">555-555-555</phone>
        <address>
            <street>12, spam road</street>
            <city>London</city>
            <zip>H4B 1X3</zip>
        </address>
    </person>
<CREATE_NEW_SUB /></addressbook>

(我希望您正在寻找的效果...?-)

(which I hope is the effect you're looking for...?-)

这篇关于Python Lxml-使用新数据附加现有的xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆