2017-08-29 5 views
0

Ich möchte Element in XML kommentieren und auskommentieren.kommentieren und kommentieren XML-Elemente mit Python

XML sieht so aus.

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

bekam ich das letzte Kind von Tag, aber ich verstehe nicht, wie das jeweilige Element kommentieren und Kommentar-, wenn nötig.

dies ist mein Code so weit:

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

Ausgang (nicht erwartet)

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

Jede Hilfe wird geschätzt.!

+0

Ich habe den Code aktualisiert und die out put bekomme ich.! was nicht erwartet wird! – tgcloud

Antwort

0

Ich habe es gelöst.! Buchungslösung hier. in Anbetracht dieser könnte jemand helfen.

Code zum Auskommentieren von 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