如何使用lxml创建具有属性的新元素? xml结构如下,
</lo>
<lo n="h" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"/>
<myconf conf="new"/> <!--- create new element with attribute -->
</lo>
<Root l="I">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</Root>
</ls>
这是我到目前为止的地方。
for logger in tree.xpath('//ls'):
if logger.get('name') == 'h':
for ref in logger.getchildren():
if len(ref.items()) == 1:
ref.getparent().replace(ref.getnext(), ref)
ref.set('ref' , 'st')
ref.set('ref' , 'new') ## This command in the script override the previous one.
tree.write(r'C:\Log_stop.xml', xml_declaration=True, encoding='UTF-8')
答案 0 :(得分:1)
#from lxml import etree
ref.getparent().append(etree.fromstring('<myconf conf="new"/>'))