0
代碼:將註釋添加到XML文檔
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)
輸出:
<?xml version='1.0' encoding='UTF-8'?>
<network>
<nodes>
<node id="1"/>
</nodes>
<links>
<link id="2"/>
</links>
</network>
上面的代碼產生此輸出。但是,除了在tostring()方法中用作參數並在文檔頂部打印的聲明之外。如果您希望他們在文檔中途說出,我還沒有弄清楚如何使評論可見。我已經看到像http://stackoverflow.com/questions/4474754/how-to-keep-comments-while-parsing-xml-using-python-elementtree,之前的帖子,但它沒有回答我的問題。有人可以幫我我怎麼可以這樣做:
<?xml version='1.0' encoding='UTF-8'?>
<network>
<nodes>
<node id="1"/>
</nodes>
<!-- ==============Some Comment============================= -->
<links>
<link id="2"/>
</links>
</network>
謝謝您的時間
請使用更具描述性的標題。另外,'xlmx'不是一件事情。 – MattDMo