我正在嘗試決議復雜的 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
我究竟做錯了什么?
uj5u.com熱心網友回復:
此 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/464284.html
上一篇:如何在選擇時更改底部導航圖示
下一篇:需要從多個元素中選擇唯一的一個值
