-1

How can i create new element with attribute with lxml ? xml structure as below,

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

This is where i reached so far.

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')  
tgcloud
  • 857
  • 6
  • 18
  • 37
  • Possible duplicate of [python lxml append element after another element](https://stackoverflow.com/questions/7474972/python-lxml-append-element-after-another-element) – stovfl Aug 30 '17 at 15:28

1 Answers1

1
#from lxml import etree
ref.getparent().append(etree.fromstring('<myconf conf="new"/>'))
Arash Rohani
  • 984
  • 1
  • 7
  • 30
  • The lxml docs mention using the `SubElement` factory as a _much more efficient and more commong_ alternative to `append()` https://lxml.de/1.3/tutorial.html#the-element-class – ccpizza Mar 08 '23 at 17:35