2017-08-29 17 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要素をコメントアウトするコード。

関連する問題