在Python中使用lxml库编写xml文件
我正在使用 lxml 从头开始创建 XML 文件; 有这样的代码:
from lxml import etree
root = etree.Element("root")
root.set("interesting", "somewhat")
child1 = etree.SubElement(root, "test")
How do I write root Element
object to an xml file using write()
method of ElementTree
class?
I'm using lxml to create an XML file from scratch;
having a code like this:
from lxml import etree
root = etree.Element("root")
root.set("interesting", "somewhat")
child1 = etree.SubElement(root, "test")
How do I write root Element
object to an xml file using write()
method of ElementTree
class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个简洁的答案,
您只需将节点放入新树中并将其写入磁盘即可。也适用于 xpath 搜索生成的
HtmlElements
。Here's a succinct answer
you simply place your node in a new tree and write that out to disk. Also works for
HtmlElements
produced by xpath searches.这对我有用:
This works for me:
您可以将文件名赋予 ElementTree 的
write()
You can give the filename to the
write()
of ElementTree您可以从元素中获取一个字符串,然后从 lxml 教程 中编写该字符串,
查看 tostring 文档以设置编码 - 这是用 Python 2 编写的,Python 3 给出了一个二进制字符串,可以直接写入文件,但可能不是您想要的代码。
或转换为元素树(最初写入文件句柄,但在我编写此文件时错过了,或者它是新的,它可以是文件名,如
You can get a string from the element and then write that from lxml tutorial
Look at the tostring documentation to set the encoding - this was written in Python 2, Python 3 gives a binary string back which can be written directly to file but is probably not what you want in code.
or convert to an element tree (originally write to a file handle but either missed when I wrote this or it is new it can be a file name as per this answer )
您可以尝试下面的代码。
You can try the below code.