如何在XML文件中查找特定标记,然后使用Python和minidom访问其父标记

时间:2011-02-10 14:56:38

标签: python xml minidom

我正在尝试编写一些代码,这些代码将搜索文章的XML文件,以查找标记中包含的特定DOI。如果找到了我想要的正确DOI,则可以访问与该DOI相关联的文章的<title><abstract>文本。

我的XML文件采用以下格式:

<root>
 <article>
  <number>
   0 
  </number>
  <DOI>
   10.1016/B978-0-12-381015-1.00004-6 
  </DOI>
  <title>
   The patagonian toothfish biology, ecology and fishery. 
  </title>
  <abstract>
   lots of abstract text
  </abstract>
 </article>
 <article>
  ...All the article tags as shown above...
 </article>
</root>

我希望脚本能够找到带有DOI 10.1016 / B978-0-12-381015-1.00004-6的文章(例如),然后让我能够访问<title>和{ {1}}标记位于相应的<abstract>标记内。

到目前为止,我已尝试调整this question的代码:

<article>

但我不完全确定我在做什么!

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

minidom是否需要?用lxml和XPath解析它会非常容易。

from lxml import etree
datasource = open('/Users/philgw/Dropbox/PW-Honours-Project/Code/processed.xml').read()
tree = etree.fromstring(datasource)
path = tree.xpath("//article[DOI="10.1016/B978-0-12-381015-1.00004-6") 

这将为您提供指定DOI的文章。

此外,标签之间似乎有空格。如果这是因为Stackoverflow格式化,我不知道。这可能是你无法与minidom匹配的原因。

答案 1 :(得分:0)

imho - 只需在python文档中查找它! 试试这个(未经测试):

from xml.dom import minidom

xmldoc = minidom.parse(datasource)   

def get_xmltext(parent, subnode_name):
    node = parent.getElementsByTagName(subnode_name)[0]
    return "".join([ch.toxml() for ch in node.childNodes])

matchingNodes = [node for node in xmldoc.getElementsByTagName("article")
           if get_xmltext(node, "DOI") == '10.1016/B978-0-12-381015-1.00004-6']

for node in matchingNodes:
    print "title:", get_xmltext(node, "title")
    print "abstract:", get_xmltext(node, "abstract")