簡體   English   中英

使用python的elementtree解析大型xml數據

[英]Parsing large xml data using python's elementtree

我目前正在學習如何使用elementtree解析xml數據。 我收到一個錯誤消息:ParseError:格式不正確(無效令牌):第1行,第2列。

我的代碼在下面,並且一些xml數據在我的代碼之后。

import xml.etree.ElementTree as ET

tree = ET.fromstring("C:\pbc.xml")
root = tree.getroot()


for article in root.findall('article'):
    print ' '.join([t.text for t in pub.findall('title')])
    for author in article.findall('author'):
        print 'Author name: {}'.format(author.text)
    for journal in article.findall('journal'):  # all venue tags with id attribute
        print 'journal'
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
<article mdate="2002-01-03" key="persons/Codd71a">
<author>E. F. Codd</author>
<title>Further Normalization of the Data Base Relational Model.</title>
<journal>IBM Research Report, San Jose, California</journal>
<volume>RJ909</volume>
<month>August</month>
<year>1971</year>
<cdrom>ibmTR/rj909.pdf</cdrom>
<ee>db/labs/ibm/RJ909.html</ee>
</article>

<article mdate="2002-01-03" key="persons/Hall74">
<author>Patrick A. V. Hall</author>
<title>Common Subexpression Identification in General Algebraic Systems.</title>
<journal>Technical Rep. UKSC 0060, IBM United Kingdom Scientific Centre</journal>
<month>November</month>
<year>1974</year>
</article>
with open("C:\pbc.xml", 'rb') as f:
    root = ET.fromstring(f.read().strip())

ET.parse不同, ET.fromstring期望包含XML內容的字符串,而不是文件名。

ET.parseET.fromstring返回根元素,而不是樹。 所以你應該省略

root = tree.getroot()

另外,您發布的XML代碼段必須以</dblp>結尾才能解析。 我認為您的真實數據具有結束標記...


xml.etree.ElementTree提供的xml.etree.ElementTree沒有tag參數,盡管lxml.etree.iterparse確實具有tag參數。

嘗試:

import xml.etree.ElementTree as ET
import htmlentitydefs

filename = "test.xml"
# http://stackoverflow.com/a/10792473/190597 (lambacck)
parser = ET.XMLParser()
parser.entity.update((x, unichr(i)) for x, i in htmlentitydefs.name2codepoint.iteritems())
context = ET.iterparse(filename, events = ('end', ), parser=parser)
for event, elem in context:
    if elem.tag == 'article':
        for author in elem.findall('author'):
            print 'Author name: {}'.format(author.text)
        for journal in elem.findall('journal'):  # all venue tags with id attribute
            print(journal.text)
        elem.clear()

注意:要使用iterparse您的XML必須是有效的,這意味着除其他外,文件開頭不能有空行。

您正在使用.fromstring()而不是.parse()

import xml.etree.ElementTree as ET

tree = ET.parse("C:\pbc.xml")
root = tree.getroot()

.fromstring()期望以字節.fromstring()而不是文件名的形式提供XML數據。

如果文檔確實很大(很多兆字節或更多),則應改用ET.iterparse()函數並清除已處理的元素:

for event, article in ET.iterparse('C:\\pbc.xml', tag='article'):
    for title in aarticle.findall('title'):
        print 'Title: {}'.format(title.txt)
    for author in article.findall('author'):
        print 'Author name: {}'.format(author.text)
    for journal in article.findall('journal'):
        print 'journal'

    article.clear()

您最好不要將xml文件的元信息放入解析器中。 如果標簽封閉良好,則解析器的效果很好。 因此,解析器可能無法識別<?xml 因此,請省略前兩行,然后重試。 :-)

暫無
暫無

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

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