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

时间:2019-07-17 17:41:56

标签: python lxml processing-instruction

如何使用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'>

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以在根元素上使用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()")