使用 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