我刚刚开始学习如何使用 minidom
解析 xml。我尝试使用以下代码获取作者姓名(xml 数据在下面):
from xml.dom import minidom
xmldoc = minidom.parse("cora.xml")
author = xmldoc.getElementsByTagName ('author')
for author in author:
authorID=author.getElementsByTagName('author id')
print authorID
我一直得到空括号([]
)。有人可以帮我吗?我还需要标题和地点。提前致谢。请参阅下面的 xml 数据:
<?xml version="1.0" encoding="UTF-8"?>
<coraRADD>
<publication id="ahlskog1994a">
<author id="199">M. Ahlskog</author>
<author id="74"> J. Paloheimo</author>
<author id="64"> H. Stubb</author>
<author id="103"> P. Dyreklev</author>
<author id="54"> M. Fahlman</author>
<title>Inganas</title>
<title>and</title>
<title>M.R.</title>
<venue>
<venue pubid="ahlskog1994a" id="1">
<name>Andersson</name>
<name> J Appl. Phys.</name>
<vol>76</vol>
<date> (1994). </date>
</venue>
最佳答案
您只能查找具有 getElementsByTagName()
的标签,而不能查找属性。您需要通过 Element.getAttribute()
method 访问这些内容相反:
for author in author:
authorID = author.getAttribute('id')
print authorID
如果您仍在学习解析 XML,那么您确实希望远离 DOM。 DOM API 过于冗长,无法适应许多不同的编程语言。
ElementTree API会更容易使用:
import xml.etree.ElementTree as ET
tree = ET.parse('cora.xml')
root = tree.getroot()
# loop over all publications
for pub in root.findall('publication'):
print ' '.join([t.text for t in pub.findall('title')])
for author in pub.findall('author'):
print 'Author id: {}'.format(author.attrib['id'])
print 'Author name: {}'.format(author.text)
for venue in pub.findall('.//venue[@id]'): # all venue tags with id attribute
print ', '.join([name.text for name in venue.findall('name')])
关于使用minidom的Python xml解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16588597/