Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.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
Python 使用重复标记读取XML_Python - Fatal编程技术网

Python 使用重复标记读取XML

Python 使用重复标记读取XML,python,Python,您可以使用findall方法获取作者的完整列表,循环遍历作者并从中生成单个字符串 for book in root.findall('book'): title = book.find('title').text author = book.find('author') year = book.find('year').text price = book.find('price').text # print(title,author,year,price)

您可以使用
findall
方法获取作者的完整列表,循环遍历作者并从中生成单个字符串

for book in root.findall('book'):
    title = book.find('title').text
    author = book.find('author')
    year = book.find('year').text
    price = book.find('price').text
    # print(title,author,year,price)

请参见
.findall
for book in root.findall('book'):
    title = book.find('title').text
    author = book.find('author')
    year = book.find('year').text
    price = book.find('price').text
    # print(title,author,year,price)
In [02]: for book in root.findall('book'): 
    ...:     title = book.find('title').text 
    ...:     # looping and joining all the authors to make single string
    ...:     author = ', '.join([auth.text for auth in book.findall('author')]) 
    ...:     year = book.find('year').text 
    ...:     price = book.find('price').text 
    ...:     print('title: {}\nauthor(s) :{}\nyear: {}\nprice: {}\n\n'.format(title, author, year, price)) 
    ...:                                                                                                                                                                                       
title: Everyday Italian
author(s) :Giada De Laurentiis
year: 2005
price: 30.00


title: Harry Potter
author(s) :J K. Rowling
year: 2005
price: 29.99


title: XQuery Kick Start
author(s) :James McGovern, Per Bothner, Kurt Cagle, James Linn, Vaidyanathan Nagarajan
year: 2003
price: 49.99


title: Learning XML
author(s) :Erik T. Ray
year: 2003
price: 39.95