在XML python中使用属性值作为过滤器
我有下面的xml文件和在XML python中使用属性值作为过滤器,python,xml,attributes,Python,Xml,Attributes,我有下面的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">
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>
"""
这个很好用
然后我尝试通过过滤来提取姓氏
使用下面的代码
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
因为您从根目录开始搜索,并且只能看到rootBookstore
的直接子目录,它们是Book
标记
请注意,由于您有许多作者居住在纽约,您可能需要找到他们:
names = [tag.text for tag in root.findall('Book/Authors/Author[@Residence="New York City"]/Last_Name')]
print(names)
>>>['Berenholtz', 'Brockmann']
此处
findall
返回一个包含作者lastnames标记的列表,您可以迭代并应用text
属性确定。知道了。也谢谢你的建议!这是有道理的。
names = [tag.text for tag in root.findall('Book/Authors/Author[@Residence="New York City"]/Last_Name')]
print(names)
>>>['Berenholtz', 'Brockmann']