使用Python声明后,如何将评论附加到XML文件?

发布于 2025-02-11 11:04:28 字数 708 浏览 1 评论 0原文

我创建一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

念﹏祤嫣 2025-02-18 11:04:28

这是一个建议。同时将XML声明和评论作为“标题”字符串提供。

from xml.etree.ElementTree import Element, tostring

header = """<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
"""

root = Element("root")
xmlstr = tostring(root).decode()

# Create a file with header + xmlstr
with open("out.xml", "w", encoding='UTF-8') as out:
    out.write(header + xmlstr)

结果中的内容in.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
<root />

Here is a suggestion. Provide both the XML declaration and the comment as a "header" string.

from xml.etree.ElementTree import Element, tostring

header = """<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
"""

root = Element("root")
xmlstr = tostring(root).decode()

# Create a file with header + xmlstr
with open("out.xml", "w", encoding='UTF-8') as out:
    out.write(header + xmlstr)

Resulting content in out.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
<root />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文