2017-08-30 10 views
-1

属性を持つ新しい要素をlxmlで作成するにはどうすればよいですか?私はこれまで達したところ以下のように XML構造は、lxmlまたは他のライブラリを使用して属性を持つ新しい子を作成する方法

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

[別の要素の後に要素を追加LXMLパイソン]の可能な重複(https://stackoverflow.com/questions/7474972/python-lxml-append-element-after-another-element) – stovfl

答えて

1
#from lxml import etree 
ref.getparent().append(etree.fromstring('<myconf conf="new"/>')) 
関連する問題