使用python注释和取消注释xml元素

时间:2017-08-29 07:52:43

标签: xml python-2.7 lxml xml-comments

我想评论和取消评论,选择XML格式的元素。

xml看起来像这样。

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

我从tag获得了最后一个孩子,但我不明白如何评论特定元素并在需要时取消注释。

到目前为止,这是我的代码:

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')

输出(不是预期的)

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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我解决了。!在此发布解决方案考虑到这可能有助于某人。!

注释掉xml元素的代码。

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