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.
是的,我不相信这是可能的,对不起。与DOM相比,ElementTree为以元素为中心的XML处理提供了一个更简单的接口,但代价是它不支持整个XML信息集。在
没有明显的方法来表示根元素之外的内容(注释、pi、doctype和XML声明),而且这些内容在解析时也会被丢弃。(旁白:这似乎包括DTD内部子集中指定的任何默认属性,这使得ElementTree严格地说是一个不兼容的XML处理器。)
{{cdu}你可以先调用一个Python{element2},然后再调用Python{1}方法。在
如果您需要对整个xmlinfoset的支持,最好还是使用DOM。在
有了lxml API,这一点再简单不过了,尽管它有点“未被充分记录”:
如果需要顶级处理指令,请按如下方式创建:
生成的文档将如下所示:
^{pr2}$他们当然应该把这个添加到他们的FAQ中,因为在我看来,这是另一个将这个优秀API区分开来的特性。在
试试
lxml
库:它遵循elementtreeapi,并添加了许多额外的功能。从compatibility overview:我知道在stdlib中不是这样,但是根据我的经验,当你需要标准元素树没有提供的东西时,这是最好的选择。在
相关问题 更多 >
编程相关推荐