我是python / lxml的新手在阅读了lxml网站并深入了解python后,我找不到解决我的n00b问题的方法。我有以下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>
</addressbook>
-------------------------------
我正在尝试将一个子节点附加到根元素,并将整个文件作为新的xml写回或者写入现有的xml。目前我写的都是一行。
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
答案 0 :(得分:16)
你可以通过复制旧树的所有来创建一个新树(不仅仅是根标记! - ),但编辑现有树要简单得多就地(以及为什么不呢? - )......:
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>
(我希望你正在寻找的效果......? - )