Skip to main content
 首页 » 编程设计

python之在 XML python 中使用属性值作为过滤器

2025年02月15日9落叶无声

我有下面的 xml 文件和

data_string = """ 
<Bookstore> 
   <Book ISBN="ISBN-13:978-1599620787" Price="15.23" Weight="1.5"> 
      <Title>New York Deco</Title> 
      <Authors> 
         <Author Residence="New York City"> 
            <First_Name>Richard</First_Name> 
            <Last_Name>Berenholtz</Last_Name> 
         </Author> 
      </Authors> 
   </Book> 
   <Book ISBN="ISBN-13:978-1579128562" Price="15.80"> 
      <Remark> 
      Five Hundred Buildings of New York and over one million other books are available for Amazon Kindle. 
      </Remark> 
      <Title>Five Hundred Buildings of New York</Title> 
      <Authors> 
         <Author Residence="Beijing"> 
            <First_Name>Bill</First_Name> 
            <Last_Name>Harris</Last_Name> 
         </Author> 
         <Author Residence="New York City"> 
            <First_Name>Jorg</First_Name> 
            <Last_Name>Brockmann</Last_Name> 
         </Author> 
      </Authors> 
   </Book> 
</Bookstore> 
""" 

我有一个关于“找到一本重 1.5 盎司的书的作者的名字”的示例代码

root.find('Book[@Weight="1.5"]/Authors/Author/First_Name').text 

这很好用。

然后我尝试通过过滤提取姓氏 通过使用下面的代码

root.find('Author[@Residence="New York City"]/Last_Name').text 

它给了我一个错误

AttributeError: 'NoneType' object has no attribute 'text' 

我该如何解决这个问题?为什么这是错误的?谢谢!

请您参考如下方法:

在这种情况下,查询应该是:

root.find('Book/Authors/Author[@Residence="New York City"]/Last_Name').text 

因为您从根开始搜索,您只能看到根 Bookstore 的直接子级,即 Book 标签。

请注意,由于您有许多作者住在纽约,您可能需要找到他们:

names = [tag.text for tag in root.findall('Book/Authors/Author[@Residence="New York City"]/Last_Name')] 
 
print(names) 
>>>['Berenholtz', 'Brockmann'] 

这里 findall 返回一个包含 authors lastnames 标签的列表,你可以迭代并应用 text 属性