向XML文档添加注释

7

代码:

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()方法参数并打印在文档顶部的声明之外,我还没有想出如何使注释可见,如果你希望它们在文档中间说到。我看过早期的帖子,比如这篇,但它没有回答我的问题。有谁能帮我解决如何做到这一点的问题吗:

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

         <!-- ==============Some Comment============================= -->
    
      <links>
        <link id="2"/>
      </links>
    </network>

请使用更具描述性的标题。此外,“xlmx”不是一个有效的东西。 - MattDMo
1个回答

15

要插入注释,您可以在代码后面这样做:

comment = etree.Comment(' === Some Comment === ')
root.insert(1, comment)  # 1 is the index where comment is inserted
如果你想在节点元素的尾部添加空格,例如nodes元素中,这可能会影响美化输出。因为一旦尾部有文本,它就不知道在哪里安全地添加空格。我想你可以使用与indent相同的技术,来自ElementLib

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接