我正在尝试解析复杂的 XML,而 xpath 的行为不像我想象的那样。这是我的示例 xml:
<project>
<samples>
<sample>show my balance</sample>
<sample>show me the <subsample value='USD'>money</subsample>today</sample>
</samples>
</project>
这是我的python代码:
from lxml import etree
somenode="<project><samples><sample>show my balance</sample><sample>show me the <subsample value='USD'>money</subsample>today</sample></samples></project>"
somenode_etree = etree.fromstring(somenode)
for x in somenode_etree.iterfind(".//sample"):
print (etree.tostring(x))
我得到输出:
b'<sample>show my balance</sample><sample>show me the <subsample value="USD">money</subsample>today</sample></samples></project>'
b'<sample>show me the <subsample value="USD">money</subsample>today</sample></samples></project>'
当我预期:
show my balance
show me the <subsample value="USD">money</subsample>today
我究竟做错了什么?
此 XPath 将按预期获取文本和元素
result = somenode_etree.xpath(".//sample/text() | .//sample/*")
result
['show my balance', 'show me the ', <Element subsample at 0x7f0516cfa288>, 'today']
根据 OP 请求打印找到的节点
for x in somenode_etree.xpath(".//sample/text() | .//sample/*[node()]"):
if type(x) == etree._Element:
print(etree.tostring(x, method='xml').decode('UTF-8'))
else:
print(x)
结果
show my balance
show me the
<subsample value="USD">money</subsample>today
today
最后一个 text() 节点被附加到前一个元素上,这似乎是方法上的一个错误etree.tostring()
!
或者
>>> for x in somenode_etree.xpath(".//sample/text() | .//sample/*"):
... if type(x) == etree._Element:
... print(x.text)
... else:
... print(x)
...
show my balance
show me the
money
today
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句