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.

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

5 个解决方案

#1


5

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

尝试lxml库:它遵循ElementTree api,并添加了许多额外的。从兼容性概述:

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.

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

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.

您可以通过将boolean remove_comments和/或remove_pis关键字参数传递给您使用的解析器来禁用此行为。为方便起见并支持可移植代码,您还可以使用etree.ETCompatXMLParser而不是默认的etree.XMLParser。它尝试提供尽可能接近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.

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

更多相关文章

  1. day05 python程序中的注释
  2. Python根据第一项从2d数组中删除元素
  3. Python ElementTree“找不到元素”异常
  4. 漂亮的LinuxC注释转换器--(2.2)目录级联转换最终实现
  5. Linux 常用命令汇总--加了注释
  6. 将现有数组中的所有元素传递给xargs
  7. 如何使用来自其他模型的信息来注释查询集,或者在Django Rest Fram
  8. PostgreSQL: array 数组类型添加元素 数组的使用
  9. PowerDesigner 生成SQL Server 2005 注释脚本

随机推荐

  1. php单引号和双引号用法
  2. php中函数的定义
  3. php怎么改端口
  4. php变量命名规则
  5. php文件上传步骤是什么
  6. php怎么改成html
  7. php连接数据库的步骤
  8. 使用PHP简单实现类似“畅言”等评论系统
  9. php怎么放大字体
  10. PHP高效生成一个不重复随机数