使用 XPath 搜尋 XML

從版本 2.7 開始,ElementTree 對 XPath 查詢有更好的支援。XPath 是一種語法,使你能夠在 xml 中導航,就像用於搜尋資料庫的 SQL 一樣。findfindall 函式都支援 XPath。下面的 xml 將用於此示例

 <Catalog>
    <Books>
        <Book id="1" price="7.95">
            <Title>Do Androids Dream of Electric Sheep?</Title>
            <Author>Philip K. Dick</Author>
        </Book>
        <Book id="5" price="5.95">
            <Title>The Colour of Magic</Title>
            <Author>Terry Pratchett</Author>
        </Book>
        <Book id="7" price="6.95">
            <Title>The Eye of The World</Title>
            <Author>Robert Jordan</Author>
        </Book>
    </Books>
</Catalog>

搜尋所有書籍:

import xml.etree.cElementTree as ET
tree = ET.parse('sample.xml')
tree.findall('Books/Book')

搜尋標題為’‘魔法的顏色’的書:

tree.find("Books/Book[Title='The Colour of Magic']") 
# always use '' in the right side of the comparison

搜尋 id = 5 的書:

tree.find("Books/Book[@id='5']")
# searches with xml attributes must have '@' before the name

搜尋第二本書:

tree.find("Books/Book[2]")
# indexes starts at 1, not 0

搜尋最後一本書:

tree.find("Books/Book[last()]")
# 'last' is the only xpath function allowed in ElementTree

搜尋所有作者:

tree.findall(".//Author")
#searches with // must use a relative path