2011-02-10 50 views
0

我正在尝试编写一些代码,用于搜索标记中包含的特定DOI文章的XML文件。当它找到正确的DOI时,我希望它可以访问与该DOI相关的文章的<title><abstract>文本。如何查找XML文件中的特定标记,然后使用Python和minidom访问其父标记

我的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(例如)和文章那么我可以访问相应的<article>标签中的<title><abstract>标签。

到目前为止,我试图从this question适应代码:

from xml.dom import minidom 

datasource = open('/Users/philgw/Dropbox/PW-Honours-Project/Code/processed.xml') 
xmldoc = minidom.parse(datasource) 

#looking for: 10.1016/B978-0-12-381015-1.00004-6 

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

for i in range(len(matchingNodes)): 
    DOI = str(matchingNodes[i]) 
    print DOI 

但我不能完全肯定我在做什么!

感谢您的任何帮助。

回答

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") 
+0

好吧,我现在看到了,你需要在matchingNodes首先寻找父母,我更新...好了,现在更新。 – Jiri 2011-02-10 16:45:58

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进行匹配的原因。

相关问题