如何在XML文件中找到特定标签并使用Python和minidom访问其父标签

0 投票
2 回答
961 浏览
提问于 2025-04-16 11:34

我正在尝试写一些代码,目的是在一个包含文章的XML文件中搜索特定的DOI(数字对象标识符),这个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的文章(比如说),然后让我能够访问对应的<article>标签中的<title><abstract>标签。

到目前为止,我尝试从这个问题中调整代码:

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

但我不太确定自己在做什么!

谢谢任何帮助。

2 个回答

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

0

在我看来 - 直接去查查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")

撰写回答