'Adding comments to xml documents
Code:
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)
Output:
<?xml version='1.0' encoding='UTF-8'?>
<network>
<nodes>
<node id="1"/>
</nodes>
<links>
<link id="2"/>
</links>
</network>
The code above produces this output. However, apart from the declaration which is used as arguments in the tostring() method and printed at the top of the document. I am yet to figure out how to make comments visible if you want them say midway in the document. I have seen earlier posts like this, but it didn't answer my question. Can someone help me with how I can do this:
<?xml version='1.0' encoding='UTF-8'?>
<network>
<nodes>
<node id="1"/>
</nodes>
<!-- ==============Some Comment============================= -->
<links>
<link id="2"/>
</links>
</network>
Solution 1:[1]
To insert a comment you can do this, after your code:
comment = etree.Comment(' === Some Comment === ')
root.insert(1, comment) # 1 is the index where comment is inserted
If you want to add spaces, for instance in the tail of the nodes
element, that may mess with prettyprint, because once there is text in tails it won't know where to add whitespace safely. I suppose you could use the same technique as indent
, from ElementLib.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Paulo Almeida |