添加注释到xml文档

时间:2016-03-30 21:58:46

标签: python 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()方法中用作参数并在文档顶部打印的声明之外。如果你想让他们在文档的中途说出来,我还没弄清楚如何让评论可见。我之前看过this这样的帖子,但它没有回答我的问题。有人可以帮助我如何做到这一点:

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

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

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

感谢您的时间

1 个答案:

答案 0 :(得分:2)

要插入评论,您可以在代码之后执行此操作:

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

如果你想添加空格,例如在nodes元素that may mess with prettyprint的尾部,因为一旦有尾部文本,它就不知道在哪里安全地添加空格。我想你可以使用indent中的<div class="_4nxi" dir="ltr"> <div class="_4nx7 _4nww _5pw0"> <div class="_4nwx"> <label style="background-color: transparent;" class="_4nx3 _5pw6" for="js_9" aria-hidden="true">7</label> <input style="background-color: rgb(255, 255, 255);" id="js_9" class="_4nx5" aria-label="hours" aria-valuetext="7" role="spinbutton"> </div> </div><span class="_4nxh _5pwa" aria-hidden="true">:</span> <div class="_4nxe _4nww _5pw0"> <div class="_4nwx"> <label class="_4nx3 _5pw6" for="js_a" aria-hidden="true">30</label> <input id="js_a" class="_4nx5" aria-label="minutes" aria-valuetext="30" role="spinbutton"> </div> </div> <div class="_4nxa _4nww _5pw0"> <div class="_4nwx"> <label class="_4nx3 _5pw6" for="js_b" aria-hidden="true">AM</label> <input id="js_b" class="_4nx5" aria-label="meridiem" aria-valuetext="AM" role="spinbutton"> </div> </div> </div> 相同的技术。