使用 Python lxml 删除处理指令

Removing Processing Instructions with Python lxml

我正在使用 python lxml 库将 XML 文件转换为新模式,但我在解析来自 XML 正文的处理指令时遇到了问题。

处理指令元素分散在整个XML中,如下例(它们都以"oasys"开始并以唯一代码结束):

string = "<text><?oasys _dc21-?>Text <i>contents</i></text>"

我无法通过 lxml.etree.findall() 方法找到它们,尽管 etree.getchildren() returns 它们:

tree = lxml.etree.fromstring(string)
print tree.findall(".//")
>>>> [<Element i at 0x747c>]
print tree.getchildren()
>>>> [<?oasys _dc21-?>, <Element i at 0x747x>]
print tree.getchildren()[0].tag
>>>> <built-in function ProcessingInstruction>
print tree.getchildren()[0].tail
>>>> Text 

除了使用 getchildren() 来解析和删除处理指令之外,是否有替代方法,特别是考虑到它们在整个 XML 中嵌套在不同的级别?

您可以使用 processing-instruction() XPath node test to find the processing instructions and remove them using etree.strip_tags().

示例:

from lxml import etree

string = "<text><?oasys _dc21-?>Text <i>contents</i></text>"
tree = etree.fromstring(string)

pis = tree.xpath("//processing-instruction()")
for pi in pis:
    etree.strip_tags(pi.getparent(), pi.tag)

print etree.tostring(tree)

输出:

<text>Text <i>contents</i></text>