使用 lxml 访问根元素之前/之后的处理指令



使用 lxml,如何访问/迭代位于根打开标签之前或根关闭标签之后的处理指令?

我已经尝试过这个,但是根据文档,它只在根元素内迭代:

import io
from lxml import etree
content = """
<?before1?>
<?before2?>
<root>text</root>
<?after1?>
<?after2?>
"""
source = etree.parse(io.StringIO(content))
print(etree.tostring(source, encoding="unicode"))
# -> <?before1?><?before2?><root>text</root><?after1?><?after2?>
for node in source.iter():
    print(type(node))
# -> <class 'lxml.etree._Element'>

我唯一的解决方案是用虚拟元素包装 XML:

dummy_content = "<dummy>{}</dummy>".format(etree.tostring(source, encoding="unicode"))
dummy = etree.parse((io.StringIO(dummy_content)))
for node in dummy.iter():
    print(type(node))
# -> <class 'lxml.etree._Element'>
#    <class 'lxml.etree._ProcessingInstruction'>
#    <class 'lxml.etree._ProcessingInstruction'>
#    <class 'lxml.etree._Element'>
#    <class 'lxml.etree._ProcessingInstruction'>
#    <class 'lxml.etree._ProcessingInstruction'>

有没有更好的解决方案?

可以在根元素上使用 getprevious()getnext() 方法。

before2 = source.getroot().getprevious()
before1 = before2.getprevious()
after1 = source.getroot().getnext()
after2 = after1.getnext()

请参阅 https://lxml.de/api/lxml.etree._Element-class.html。


也可以使用 XPath(在 ElementTreeElement实例上(:

before = source.xpath("preceding-sibling::node()")  # List of two PIs
after = source.xpath("following-sibling::node()")

相关内容

  • 没有找到相关文章

最新更新