使用Python声明后,如何将评论附加到XML文件?
我创建一个root:
from xml.etree.ElementTree import Element, tostring
root = Element("root")
然后生成XML的字符串repr:
xmlstr = tostring(root, encoding="utf8", method="xml")
并创建我的XML文件:
myFile = open(file, "w")
myFile.write(xmlstr)
myFile.close()
在所有操作之后,我的文件看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<root>
</root>
在XML声明之后我该怎么做才能添加一些注释?尝试使用xml.etree.elementtree.com,但不确定如何正确执行。我理想的文件应该看起来:
<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
<root>
</root>
随时询问您是否不了解某些内容。谢谢!
I create a root:
from xml.etree.ElementTree import Element, tostring
root = Element("root")
Then generating a string repr of XML:
xmlstr = tostring(root, encoding="utf8", method="xml")
And create my xml file:
myFile = open(file, "w")
myFile.write(xmlstr)
myFile.close()
After all operations my file looks like that:
<?xml version="1.0" encoding="UTF-8"?>
<root>
</root>
What I should do to add some comments after xml declaration? Tried to use xml.etree.ElementTree.Comment but not sure how to do it properly. My desirable file should looks:
<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
<root>
</root>
Feel free to ask if you don't understand something. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个建议。同时将XML声明和评论作为“标题”字符串提供。
结果中的内容in.xml:
Here is a suggestion. Provide both the XML declaration and the comment as a "header" string.
Resulting content in out.xml: