comment and uncomment xml elements with python

1.4k views Asked by At

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.!

1

There are 1 answers

0
tgcloud On

I got it solved.! posting solution here. considering this might help someone.!

Code to comment out xml element.

def comment_element(tree, name):
    for logger in tree.xpath('//ls'):
        if logger.get('name') == 'h':
            for ref in logger.getchildren():
                if ref.get('conf') == 'st':
                    ref.getparent().replace(ref, etree.Comment(etree.tostring(ref)))
    return tree

def uncomment_child(tree, name):
    for clogger in tree.xpath('//logger'):
        if clogger.get('name') == 'h':
            for ref in clogger.getchildren():
                if len(ref.items()) == 1:
                    ref.getparent().replace(ref.getnext(), ref) 
                    ref.getparent().append(etree.fromstring('<AppenderRef ref="STDOUT"/>'))

    return tree