lxml 删除 解析时的标签?

发布于 2024-09-09 03:38:45 字数 475 浏览 1 评论 0 原文

我目前正在解析 XML 文档(添加元素、添加属性等)。因此,我首先需要在处理 XML 之前对其进行解析。但是,lxml 似乎正在删除元素 。例如,

from lxml import etree

tree = etree.fromstring('<?xml version="1.0" encoding="utf-8"?><dmodule>test</dmodule>', etree.XMLParser())
print etree.tostring(tree)

将导致

<dmodule>test</dmodule>

有人知道为什么 元素被删除吗?我认为编码标签是有效的 XML。感谢您抽出时间。

I'm currently working with parsing XML documents (adding elements, adding attributes, etc). So I first need to parse the XML in before working on it. However, lxml seems to be removing the element <?xml ...>. For example

from lxml import etree

tree = etree.fromstring('<?xml version="1.0" encoding="utf-8"?><dmodule>test</dmodule>', etree.XMLParser())
print etree.tostring(tree)

will result in

<dmodule>test</dmodule>

Does anyone know why the <?xml ...> element is being removed? I thought encoding tags were valid XML. Thanks for your time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

野の 2024-09-16 03:38:45

元素是 XML 声明,因此严格来说它不是一个元素。它仅提供有关其下面的 XML 树的信息。

如果您需要使用 lxml 打印出来,这里有一些关于您可以使用的 xmlDeclaration=TRUE 标志的信息。

http://lxml.de/api.html#serialization

etree.tostring(tree, xml_declaration=True)

The <?xml> element is an XML declaration, so it's not strictly an element. It just gives info about the XML tree below it.

If you need to print it out with lxml, there is some info here about the xmlDeclaration=TRUE flag you can use.

http://lxml.de/api.html#serialisation

etree.tostring(tree, xml_declaration=True)
清秋悲枫 2024-09-16 03:38:45

有谁知道为什么 元素被删除?

XML 默认为 UTF-8 格式的版本 1.0,因此如果删除它们,文档是等效的。

您正在将某些 XML 解析为数据结构,然后将该数据结构转换回 XML。您将获得该数据结构的 XML 表示形式,但它可能不会以相同的方式表示(因此可以删除序言,并且 可以与 交换 等等)。

Does anyone know why the <?xml ...> element is being removed?

XML defaults to version 1.0 in UTF-8 so the document is equivalent if you remove them.

You are parsing some XML to a data structure and then converting that data structure back to XML. You will get a representation of that data structure in XML, but it might not be expressed in the same way (so the prolog can be removed and <foo /> can be exchanged with <foo></foo> and so on).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文