I would like to comment and un-comment, selected element in XML.
xml looks like this.
<ls>
<lo n="x" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="s" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"/> <!-- would like to comment this element and uncomment when needed -->
</lo>
<lo n="v" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="h" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"/> <!--- would like to comment this element and uncomment when needed-->
</lo>
<Root l="I">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</Root>
</ls>
I got the last child from tag, however i dont understand how to comment the particular element and uncomment when needed.
this is my code so far:
from lxml import etree
tree = etree.parse(r'C:\stop.xml')
for logger in tree.xpath('//logger'):
if logger.get('name') == 'h':
for ref in logger.getchildren():
if ref.get('ref') == 'STDOUT':
ref.append(etree.Comment(' '))
tree.write(r'C:\Log_start.xml', xml_declaration=True, encoding='UTF-8')
output (not expected)
<ls>
<lo n="x" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="s" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"/> <!-- would like to comment this element and uncomment when needed -->
</lo>
<lo n="v" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="h" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"><!-- --></myconf> <!--- would like to comment this element and uncomment when needed-->
</lo>
<Root l="I">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</Root>
</ls>
Any help will be appreciated.!
I got it solved.! posting solution here. considering this might help someone.!
Code to comment out xml element.