【问题标题】:comment and uncomment xml elements with python使用 python 注释和取消注释 xml 元素
【发布时间】:2017-08-29 07:52:43
【问题描述】:

我想对 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>

我从标签中得到了最后一个孩子,但是我不明白如何评论特定元素并在需要时取消评论。

这是我目前的代码:

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>

任何帮助将不胜感激。!

【问题讨论】:

  • 我已经更新了代码和我得到的输出。!这是意料之外的!

标签: xml python-2.7 lxml xml-comments


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-19
    • 2017-12-24
    • 2012-12-08
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2020-09-27
    • 2013-03-11
    相关资源
    最近更新 更多