在文档开头添加注释 [英] Add comment to beginning of document
本文介绍了在文档开头添加注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用ElementTree,如何在XML声明下方和根元素上方放置注释?
Using ElementTree, how do I place a comment just below the XML declaration and above the root element?
我尝试了 root.append (评论)
,但这会将评论放置为 root
的最后一个子项。我可以在 root
的父母后面加上注释吗?
I have tried root.append(comment)
, but this places the comment as the last child of root
. Can I append the comment to whatever is root
's parent?
谢谢。
推荐答案
以下是使用 lxml ,使用 addprevious()
方法。
Here is how a comment can be added in the wanted position (after XML declaration, before root element) with lxml, using the addprevious()
method.
from lxml import etree
root = etree.fromstring('<root><x>y</x></root>')
comment = etree.Comment('This is a comment')
root.addprevious(comment) # Add the comment as a preceding sibling
etree.ElementTree(root).write("out.xml",
pretty_print=True,
encoding="UTF-8",
xml_declaration=True)
结果(out.xml):
Result (out.xml):
<?xml version='1.0' encoding='UTF-8'?>
<!--This is a comment-->
<root>
<x>y</x>
</root>
这篇关于在文档开头添加注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文