Python Lxml - Append a existing xml with new data

孤街浪徒 提交于 2019-12-05 05:49:49

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

which puts in 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...?-)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!