2017-08-29 55 views
0

我想對XML中的選定元素進行評論和取消註釋。使用python評論和取消註釋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> 

任何幫助將不勝感激!

+0

我有更新的代碼和出來,我越來越。這不是預期! – tgcloud

回答

0

我解決了它!在此發佈解決方案考慮到這可能會幫助別人。

代碼註釋掉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