python - Python 2.6.2 中的 ElementTree 处理指令支持吗?

标签 python xml elementtree

我正在尝试使用 Python 中的 ElementTree 对象结构创建 XML。除了处理指令外,一切都很好。我可以使用工厂函数 ProcessingInstruction() 轻松创建 PI,但它不会添加到元素树中。我可以手动添加它,但我不知道如何将它添加到通常放置 PI 的根元素之上。有人知道怎么做吗?我知道有很多替代方法可以做到这一点,但似乎这必须建立在我找不到的地方。

最佳答案

尝试使用 lxml 库:它遵循 ElementTree api,并添加了很多额外功能。来自compatibility overview :

ElementTree ignores comments and processing instructions when parsing XML, while etree will read them in and treat them as Comment or ProcessingInstruction elements respectively. This is especially visible where comments are found inside text content, which is then split by the Comment element.

You can disable this behaviour by passing the boolean remove_comments and/or remove_pis keyword arguments to the parser you use. For convenience and to support portable code, you can also use the etree.ETCompatXMLParser instead of the default etree.XMLParser. It tries to provide a default setup that is as close to the ElementTree parser as possible.

不在 stdlib 中,我知道,但根据我的经验,当您需要标准 ElementTree 不提供的东西时,这是最好的选择。

关于python - Python 2.6.2 中的 ElementTree 处理指令支持吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1489949/

相关文章:

c# - 嵌套列表 C# 的 XML 反序列化

python - 如果特定属性匹配,则查找并提取 xml 标签的名称

Python 2.7 和 xml.etree : how to create an XML file with multiple namespaces?

android - 您可以在 Android 上的 XML 属性值中使用公式吗?

c# - 即使元素确实存在,LINQ to XML Elements() 和 Descendants() 也没有产生任何结果

python - 使用 ElementTree 解析带有特殊字符的 XML

python - 如何从ftp下载文件?

Python:获取类型 `typing.List`

python - 从单个 json 对象加载数据帧

python - 显示模板中存储为二进制 blob 的图像