Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在XML python中使用属性值作为过滤器_Python_Xml_Attributes - Fatal编程技术网

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

在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">

我有下面的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>
"""
这个很好用

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

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
因为您从根目录开始搜索,并且只能看到root
Bookstore
的直接子目录,它们是
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']