使用元素树从 python 中的文件中读取 XML 数据

Reading XML data from a file in python using Element tree

我正在尝试打印我的 xml 文件中的数据,但使用 ElementTree 没有帮助。数据已成功写入文件 'data.xml',但无法读取,控制台以退出代码 0 终止,未显示任何数据。 'data.findall' 循环甚至没有进入。

import urllib2
import xml.etree.ElementTree as ET

def main():
    search_url = "http://export.arxiv.org/api/query?search_query=all:social+science&start=0&max_results=10&sortBy=submittedDate&sortOrder=descending"
    file1 = open("data.xml", 'w')
    file1.write(''.join(map(str, urllib2.urlopen(search_url))))
    file1.close()
    print_data()    

def print_data():
    data = ET.parse('data.xml').getroot()
    for child in data.findall('entry'):
        print "Title :" + child.find('title').text + "\n"
        print "hahah"
        print "Summary :" + child.find('summary').text + "\n"
        print "Published On :" + child.find('published').text + "\n"
        for grab in child.find('link'):
            if grab.get('type') == 'application/pdf':
                print "Download Link :" + grab.get('href').text
                link = grab.get('href').text
                get_data = urllib2.urlopen(link)
                file2 = open('paper.pdf', 'w')
                file2.write(get_data.read())
                file2.close()
if __name__ == "__main__":
    main()

您需要将命名空间与标签名称一起传递给 findall。

替换为:

for child in data.findall('entry'):

有了这个:

for child in data.findall('{http://www.w3.org/2005/Atom}entry'):

其中 http://www.w3.org/2005/Atom 是 data.xml

中根元素的 xmlns 属性的值

Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes: https://docs.python.org/2/library/xml.etree.elementtree.html

所以,我试着找到:

def print_data():
    data = ET.parse('data.xml').getroot()
    for child in data.findall('entry'):
        for entry in child.findall('entry'):
            print entry

此代码找到所有条目,为什么很多条目不是直接子项,我现在不知道。