我是 XPath 的新手,正在使用一個如下所示的 XML 檔案:
<doc>
<component>
<author> Bob </author>
</component>
<component>
<sB>
<component>
<section ID='S1'>
<title>Some s1 title</title>
</section>
</component>
<component>
<section ID='S2'>
<title>Some s2 title</title>
</section>
</component>
</sB>
</component>
</doc>
我想檢索上面帶有部分 ID = S1 的組件項,或者具有帶有文本“Some s1 title”的標題元素的項。我不能指望這些東西按特定順序排列。
到目前為止我已經嘗試過
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
res = tree.getroot().findall(".//*[title='Some s1 title']../../")
for i in res:
ET.dump(i)
但這讓我得到了兩個組件,而不僅僅是具有匹配標題的組件。
我還嘗試在部分 ID 級別進行搜索,如下所示:
res = tree.getroot().findall(".//*section[@ID='S1']/../")
for i in res:
ET.dump(i)
但這并沒有讓我成為父級(整個組件),而只是讓我獲得了該部分。
這兩個似乎都可以從我在網上看到的簡單示例語法中作業,但很明顯,在這兩種情況下,我都缺少對實際發生的事情的一些了解。有人可以澄清這里發生的事情以及為什么我沒有得到我所期望的嗎?
uj5u.com熱心網友回復:
制作您的 XPath 運算式以進行選擇component,然后使用謂詞(方括號內的條件)來確定components您想要的。如:
component包含sectionwith ID= 'S1'
//component[./section[@ID='S1']]
或component包含section/title= 'Some s1 title'
//component[./section/title/text() = 'Some s1 title']
或包含sectionID = 'S1' 且section具有title= 'Some s1 title' 的組件
//component[./section[@ID='S1']/title/text() = 'Some s1 title']
和其他變化是可能的。
uj5u.com熱心網友回復:
您的兩個 XPath 都存在語法錯誤:
.//*[title='Some s1 title']../..//在謂詞之后缺少一個。那么這個無論如何都會向上超調。.//*section[@ID='S1']/../不能有一個*beforesection。否則這個會起作用。
但是,與其修復和從那里開始作業,您實際上并不需要沿父軸或祖先軸進行選擇 - 無論如何最好使用層次結構中更高的謂詞......
這個 XPath,
//component[section/@ID='S1']
選擇具有屬性值等于 的子component元素的元素。sectionid'S1'
這個 XPath,
//component[section/title='Some s1 title']
選擇子component元素的section子元素,其子元素title的字串值等于'Some s1 title'。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/337084.html
