Python/ElementTree:解析内嵌元素时考虑到周围的文本?

2024-06-08 04:49:10 发布

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

我需要解析一些包含内联元素的XML。例如,XML的外观如下:

<section> Fubar, I'm so fubar, fubar and even more <fref bar="baz">fubare</fref>. And yet more fubar. </section>

如果我现在用for elem in list(parent): ...遍历这个结构,我只能访问fref。如果我现在处理fref,周围的文本当然会丢失,因为文本不是真正的元素。在

有没有人知道一个正确解决这个问题的方法?在


Tags: and文本元素somorebarsectionxml
1条回答
网友
1楼 · 发布于 2024-06-08 04:49:10

下面展示了如何使用lxml来实现这一点。在

>>> from lxml.etree import fromstring
>>> tree = fromstring('''<section> Fubar, I'm so fubar, fubar and even more <fref bar="baz">fubare</fref>. And yet more fubar. </section>''')
>>> elem = tree.xpath('/section/fref')[0]
>>> elem.text
'fubare'
>>> elem.tail
'. And yet more fubar. '
>>> elem.getparent().text
" Fubar, I'm so fubar, fubar and even more "

来自lxml.etreetutorial

If you want to read only the text, i.e. without any intermediate tags, you have to recursively concatenate all text and tail attributes in the correct order. Again, the tostring() function comes to the rescue, this time using the method keyword:

^{pr2}$

还有一种XPath方法可以实现这一点,在链接页面中有描述。在

相关问题 更多 >

    热门问题