Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向xml文档添加注释_Python_Xml - Fatal编程技术网

Python 向xml文档添加注释

Python 向xml文档添加注释,python,xml,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') elemen

代码:

输出:

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)

上面的代码生成此输出。但是,除了在tostring()方法中用作参数并打印在文档顶部的声明之外。我还没有弄清楚,如果你想让评论在文档的中途出现,如何让评论可见。我以前看到过类似的帖子,但没有回答我的问题。有人能帮我怎么做吗:

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


感谢您抽出时间插入注释。您可以在代码后插入注释:

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

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

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

如果要添加空格,例如在
节点
元素的尾部,因为一旦尾部有文本,它就不知道在哪里安全地添加空白。我想您可以使用与缩进相同的技巧。

请使用更具描述性的标题。而且,
xlmx
也不是什么东西。
comment = etree.Comment(' === Some Comment === ')
root.insert(1, comment)  # 1 is the index where comment is inserted