相关疑难解决方法(0)

在Parsed XML中忠实地保留注释(Python 2.7)

在操作XML时,我希望尽可能忠实地保留注释.

我设法保留了评论,但内容正在进行XML转义.

#!/usr/bin/env python
# add_host_to_tomcat.py

import xml.etree.ElementTree as ET
from CommentedTreeBuilder import CommentedTreeBuilder
parser = CommentedTreeBuilder()

if __name__ == '__main__':
    filename = "/opt/lucee/tomcat/conf/server.xml"

    # this is the important part: use the comment-preserving parser
    tree = ET.parse(filename, parser)

    # get the node to add a child to
    engine_node = tree.find("./Service/Engine")

    # add a node: Engine.Host
    host_node = ET.SubElement(
        engine_node,
        "Host",
        name="local.mysite.com",
        appBase="webapps"
    )
    # add a child to new node: Engine.Host.Context
    ET.SubElement(
        host_node,
        'Context',
        path="",
        docBase="/path/to/doc/base"
    )

    tree.write('out.xml')
Run Code Online (Sandbox Code Playgroud)
#!/usr/bin/env python …
Run Code Online (Sandbox Code Playgroud)

python xml elementtree python-2.7

13
推荐指数
4
解决办法
6979
查看次数

向 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)
Run Code Online (Sandbox Code Playgroud)

输出:

<?xml version='1.0' encoding='UTF-8'?>
<network>
  <nodes>
    <node id="1"/>
  </nodes>
  <links>
    <link id="2"/>
  </links>
</network>
Run Code Online (Sandbox Code Playgroud)

上面的代码产生这个输出。但是,除了在 tostring() 方法中用作参数并打印在文档顶部的声明之外。如果您希望评论在文档中途说出来,我还没有弄清楚如何使评论可见。我见过像前面的帖子这样,但它并没有回答我的问题。有人可以帮助我如何做到这一点:

<?xml version='1.0' encoding='UTF-8'?> …
Run Code Online (Sandbox Code Playgroud)

python xml

4
推荐指数
1
解决办法
7705
查看次数

标签 统计

python ×2

xml ×2

elementtree ×1

python-2.7 ×1