Kodu:yorum eklenmesi
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)
Çıktı:
<?xml version='1.0' encoding='UTF-8'?>
<network>
<nodes>
<node id="1"/>
</nodes>
<links>
<link id="2"/>
</links>
</network>
Yukarıdaki kod bu çıktıyı üretir. Ancak, tostring() yönteminde argüman olarak kullanılan ve belgenin en üstünde basılan beyan dışında. Belgedeki dosyaların ortada kalmasını istiyorsanız yorumların nasıl görünür hale getirileceğini henüz anlamadım. http://stackoverflow.com/questions/4474754/how-to-keep-comments-while-parsing-xml-using-python-elementtree, gibi daha önceki yazıları gördüm ancak soruma cevap vermedi. İsterseniz
comment = etree.Comment(' === Some Comment === ')
root.insert(1, comment) # 1 is the index where comment is inserted
:
<?xml version='1.0' encoding='UTF-8'?>
<network>
<nodes>
<node id="1"/>
</nodes>
<!-- ==============Some Comment============================= -->
<links>
<link id="2"/>
</links>
</network>
Kodunuzdaki sonra, bunu bir açıklama eklemek için zaman
Lütfen daha açıklayıcı bir başlık kullanın. Ayrıca, xlmx' bir şey değil. – MattDMo