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'>
より良い解決策はありますか?