簡體   English   中英

使用Element樹從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()僅查找帶有標記的元素,這些元素是當前元素的直接子元素。 Element.find()查找具有特定標記的第一個子元素,Element.text訪問元素的文本內容。 Element.get()訪問元素的屬性: 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

並且這段代碼找到所有條目,為什么很多條目都不是直接的孩子,我現在不用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM