我正在尝试使用 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/orremove_pis
keyword arguments to the parser you use. For convenience and to support portable code, you can also use theetree.ETCompatXMLParser
instead of the defaultetree.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/