2016-03-30 15 views
0

Code:Hinzufügen von Kommentaren zu XML-Dokumenten

from lxml import etree 

# Create the network XML file tree 
root = etree.Element('network') 
tree = etree.ElementTree(root) 

# Create the nodes data 
name = etree.Element('nodes') 
root.append(name) 
element = etree.SubElement(name, 'node') 
element.set('id', '1') 

# Create the links data 
name = etree.Element('links') 
root.append(name) 
element = etree.SubElement(name, 'link') 
element.set('id', '2') 

# Print document to screen 
print etree.tostring(root, encoding='UTF-8', xml_declaration=True, pretty_print=True) 

Ausgang:

<?xml version='1.0' encoding='UTF-8'?> 
<network> 
    <nodes> 
    <node id="1"/> 
    </nodes> 
    <links> 
    <link id="2"/> 
    </links> 
</network> 

Der obige Code diesen Ausgang erzeugt. Allerdings abgesehen von der Deklaration, die als Argumente in der Methode totring() verwendet und am Anfang des Dokuments gedruckt wird. Ich habe noch nicht herausgefunden, wie man Kommentare sichtbar macht, wenn man möchte, dass sie in der Mitte des Dokuments stehen. Ich habe frühere Beiträge wie http://stackoverflow.com/questions/4474754/how-to-keep-comments-while-parsing-xml-using-python-elementtree, gesehen, aber es hat meine Frage nicht beantwortet. Kann mir jemand helfen mit, wie ich das tun kann:

<?xml version='1.0' encoding='UTF-8'?> 
    <network> 
     <nodes> 
     <node id="1"/> 
     </nodes> 

     <!-- ==============Some Comment============================= --> 

     <links> 
     <link id="2"/> 
     </links> 
    </network> 

Dank für Ihre Zeit danken

+0

Bitte verwenden Sie einen aussagekräftigeren Titel. Auch 'xlmx' ist keine Sache. – MattDMo

Antwort

2

einen Kommentar fügen Sie dies tun können, nachdem Ihr Code:

comment = etree.Comment(' === Some Comment === ') 
root.insert(1, comment) # 1 is the index where comment is inserted 

Wenn Sie möchten, zum Beispiel Leerzeichen im nodes -Element, that may mess with prettyprint, denn sobald Text in Tails ist, weiß es nicht, wo Whitespace sicher hinzugefügt werden soll. Ich nehme an, Sie könnten die gleiche Technik wie indent, von ElementLib verwenden.

Verwandte Themen