Python2.6.2中的ElementTree处理指令支持吗?

2024-06-26 18:02:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用python中的ElementTree对象结构创建XML。除了在处理指令方面,它都能很好地工作。我可以使用工厂函数ProcessingInstruction()轻松地创建一个PI,但它不能添加到elementtree中。我可以手动添加它,但是我不知道如何将它添加到通常放置PI的根元素之上。有人知道怎么做吗?我知道有很多其他的方法来做这件事,但似乎这必须建立在我找不到的地方。在


Tags: 对象方法函数元素工厂地方指令pi
3条回答

是的,我不相信这是可能的,对不起。与DOM相比,ElementTree为以元素为中心的XML处理提供了一个更简单的接口,但代价是它不支持整个XML信息集。在

没有明显的方法来表示根元素之外的内容(注释、pi、doctype和XML声明),而且这些内容在解析时也会被丢弃。(旁白:这似乎包括DTD内部子集中指定的任何默认属性,这使得ElementTree严格地说是一个不兼容的XML处理器。)

{{cdu}你可以先调用一个Python{element2},然后再调用Python{1}方法。在

如果您需要对整个xmlinfoset的支持,最好还是使用DOM。在

有了lxml API,这一点再简单不过了,尽管它有点“未被充分记录”:

如果需要顶级处理指令,请按如下方式创建:

from lxml import etree

root = etree.Element("anytagname")
root.addprevious(etree.ProcessingInstruction("anypi", "anypicontent"))

生成的文档将如下所示:

^{pr2}$

他们当然应该把这个添加到他们的FAQ中,因为在我看来,这是另一个将这个优秀API区分开来的特性。在

试试lxml库:它遵循elementtreeapi,并添加了许多额外的功能。从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中不是这样,但是根据我的经验,当你需要标准元素树没有提供的东西时,这是最好的选择。在

相关问题 更多 >