Python 2.6.2处理指令中的ElementTree是否支持? [英] ElementTree in Python 2.6.2 Processing Instructions support?

查看:62
本文介绍了Python 2.6.2处理指令中的ElementTree是否支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python中的ElementTree对象结构创建XML。除涉及处理指令外,所有其他功能都非常有效。我可以使用工厂函数ProcessingInstruction()轻松创建一个PI,但不会将其添加到elementtree中。我可以手动添加它,但是我不知道如何在通常放置PI的根元素上方添加它。有人知道怎么做吗?我知道有很多替代方法,但似乎必须将其构建在我找不到的地方。

I'm trying to create XML using the ElementTree object structure in python. It all works very well except when it comes to processing instructions. I can create a PI easily using the factory function ProcessingInstruction(), but it doesn't get added into the elementtree. I can add it manually, but I can't figure out how to add it above the root element where PI's are normally placed. Anyone know how to do this? I know of plenty of alternative methods of doing it, but it seems that this must be built in somewhere that I just can't find.

推荐答案

尝试使用 lxml 库:它遵循ElementTree api,并添加了许多附加功能。从兼容性概述

Try the lxml library: it follows the ElementTree api, plus adds a lot of extras. From the compatibility overview:


当解析XML时,ElementTree会忽略注释和处理指令,而etree会读取它们并将它们分别视为Comment或ProcessingInstruction元素。在文本内容中找到注释后,注释尤其明显。

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.

您可以通过传递布尔值 remove_comments 来禁用此行为。 code>和/或 remove_pis 关键字参数用于您使用的解析器。为了方便起见并支持可移植代码,您还可以使用 etree.ETCompatXMLParser 代替默认的 etree.XMLParser 。它会尝试提供一个尽可能接近ElementTree解析器的默认设置。

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不提供的东西时,最好的选择。

Not in the stdlib, I know, but in my experience the best bet when you need stuff that the standard ElementTree doesn't provide.

这篇关于Python 2.6.2处理指令中的ElementTree是否支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆