使用lxm访问根元素前后的处理说明

2024-09-20 22:54:06 发布

您现在位置:Python中文网/ 问答频道 /正文

使用lxml,如何访问/迭代位于根open标记之前或根close标记之后的处理指令?你知道吗

我尝试过这个方法,但是根据文档,它只在根元素中迭代:

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'>

有更好的解决办法吗?你知道吗


Tags: 标记ioimportnode元素sourcerootelement
1条回答
网友
1楼 · 发布于 2024-09-20 22:54:06

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

相关问题 更多 >

    热门问题