使用 lxml,如何在根元素之前添加处理指令或使用 lxml 在根元素之后附加 PI。
目前,以下示例不起作用:
from lxml import etree
root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
print(etree.tounicode(root))
我得到:
<ROOT/>
代替:
<?foo?><ROOT/>
最佳答案
实际上,一个 Element
始终附加到 ElementTree
即使它看起来“分离”:
root = etree.XML("<ROOT/>")
assert root.getroottree() is not None
当我们使用 addprevious
/addnext
在根元素之前/之后插入处理指令时,PI 不附加到父元素(没有任何) 但它们附加到根树。
所以,问题出在tounicode
的用法上(或 tostring
)。最佳做法是打印根树的 XML,而不是根元素。
from lxml import etree
root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
root.addnext(etree.ProcessingInstruction("bar"))
print(etree.tounicode(root))
# => "<ROOT/>"
print(etree.tounicode(root.getroottree()))
# => "<?foo ?><ROOT/><?bar ?>"
关于python - 使用 lxml 在根元素之前/之后添加或追加 PI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60217386/