使用Python xml.etree.ElementTree遍历XML树的问题

时间:2019-01-31 17:51:36

标签: python xml

我有一个如下所示的XML文件结构(此问题已简化)。对于每条记录,我想提取文章标题和“ ArticleId”元素中包含DOI号的属性“ IdType”的值(有时可能会缺少此属性),然后将文章标题存储在具有DOI的字典中作为关键。

<PubmedArticleSet>
<PubmedArticle>
    <MedlineCitation Status="MEDLINE" Owner="NLM">
        <Article PubModel="Print-Electronic">
            <ArticleTitle>Malathion and dithane induce DNA damage in Vicia faba.</ArticleTitle>
        </Article>
    </MedlineCitation>  
    <PubmedData>
        <ArticleIdList>
            <ArticleId IdType="pubmed">28950791</ArticleId>
            <ArticleId IdType="doi">10.1177/0748233717726877</ArticleId>
        </ArticleIdList>
    </PubmedData>
</PubmedArticle>

<PubmedArticle>
    <MedlineCitation Status="MEDLINE" Owner="NLM">
        <Article PubModel="Print-Electronic">
            <ArticleTitle>Impact of dual inoculation with Rhizobium and PGPR on growth and antioxidant status of Vicia faba L. under copper stress.</ArticleTitle>
        </Article>
    </MedlineCitation>  
    <PubmedData>
        <ArticleIdList>
            <ArticleId IdType="pubmed">25747267</ArticleId>
            <ArticleId IdType="pii">S1631-0691(15)00050-5</ArticleId>
            <ArticleId IdType="doi">10.1016/j.crvi.2015.02.001</ArticleId>
        </ArticleIdList>
    </PubmedData>
</PubmedArticle>

<PubmedArticle>
    <MedlineCitation Status="MEDLINE" IndexingMethod="Curated" Owner="NLM">
        <Article PubModel="Print-Electronic">
            <ArticleTitle>[Influence of Four Kinds of PPCPs on Micronucleus Rate of the Root-Tip Cells of Vicia-faba and Garlic].</ArticleTitle>
        </Article>
    </MedlineCitation>
    <PubmedData>
    <ArticleIdList>
        <ArticleId IdType="pubmed">27548984</ArticleId>
        <!-- in this record, DOI is missing -->
    </ArticleIdList>
    </PubmedData>
</PubmedArticle>
</PubmedArticleSet>

为了实现这一目标,我la脚使用xml.etree.ElementTree,如下所示:

import xml.etree.ElementTree as ET

xmldoc = ET.parse('sample.xml')
root = xmldoc.getroot()
pubs = {}
for elem in xmldoc.iter(tag='ArticleTitle'):
    title = elem.text
    for subelem in xmldoc.iter(tag='ArticleId'):
        if subelem.get("IdType") == "doi":
            doi = subelem.text 
            pubs[doi] = title

if len(pubs) == 0:
   print "No articles found"
else:   
   for pub in pubs.keys():
       print pub + ' ' + pubs[pub]

但是遍历文档树的循环存在问题,因为上面的代码导致:

10.1177/0748233717726877 [Influence of Four Kinds of PPCPs on Micronucleus Rate of the Root-Tip Cells of Vicia-faba and Garlic].
10.1016/j.crvi.2015.02.001 [Influence of Four Kinds of PPCPs on Micronucleus Rate of the Root-Tip Cells of Vicia-faba and Garlic].

也就是说,我得到了正确的DOI,而只是上一篇文章标题的重复,而没有DOI!

正确的输出应为:

10.1177/0748233717726877 Malathion and dithane induce DNA damage in Vicia faba.
10.1016/j.crvi.2015.02.001 Impact of dual inoculation with Rhizobium and PGPR on growth and antioxidant status of Vicia faba L. under copper stress.

有人可以给我一些解决这个烦人问题的提示吗?

1 个答案:

答案 0 :(得分:1)

这从根本上是错误的:

for elem in xmldoc.iter(tag='ArticleTitle'):      # <-- *ALL* <ArticleTitle> elements
    ...
    for subelem in xmldoc.iter(tag='ArticleId'):  # <-- *ALL* <ArticleId> elements
        ...

ElementTree中没有什么值得一读的内容,它只会选择与您碰巧看到的最后一个<ArticleId>相关的<ArticleTitle>,因此,使用该代码找到的任何内容实际上都不会相关

围绕实际XML文档构建代码(“为每个PubmedArticle ...” ),并使用相对搜索:

pubs = []

for pubmedArticle in xmldoc.iter(tag='PubmedArticle'):  
    # relative search within this <PubmedArticle>
    articleTitle = pubmedArticle.find('./MedlineCitation/Article/ArticleTitle')

    # always verify that there are actual results for a search
    if articleTitle == None:
       title = "No article title found"
    else:
       title = articleTitle.text

    for articleId in pubmedArticle.iterfind('./PubmedData//ArticleId'):
        if articleId.get("IdType") == "doi":
            pubs.append({"doi": articleId.text, "title": title})

我还建议列出一个词典列表,而不是一个词典。在您的以下代码中将更容易处理:

[
    {'doi': '10.1177/0748233717726877', 'title': 'Malathion and dithane induce DNA damage in Vicia faba.'},
    {'doi': '10.1016/j.crvi.2015.02.001', 'title': 'Impact of dual inoculation with Rhizobium and PGPR on growth and antioxidant status of Vicia faba L. under copper stress.'}
]