2

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

より良い解決策はありますか?

4

1 に答える 1

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 を (ElementTreeまたはElementインスタンスで) 使用することも可能です。

before = source.xpath("preceding-sibling::node()")  # List of two PIs
after = source.xpath("following-sibling::node()")
于 2019-07-17T18:51:58.193 に答える