使用minidom的Python xml解析

标签 python xml parsing

我刚刚开始学习如何使用 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/

相关文章:

python - 这种方法是否有更快的替代方法来从字典列表中获取最后更新消息?

python - 按颜色计算加载到 numpy 数组中的图像的像素数

java - 使用HashMap和List解析文本文件

node.js - 如何在 express 权限中使用 "cookie-parser"以及 socket.io 中的 cookie 在哪里?

java - fatal error : 'com.ibm.xtq.commons.utils.wrappedruntimeexception : the root element is required ina well formed document'

java - 'create table as ..' 查询的 JSqlParser

python - 无法理解 HTTP 请求处理函数如何访问 Tornado 中的应用程序对象

python - 如果我使用变量,如何在打印语句中包含引号

java - 带有图像背景的欢迎 Activity

java - 单击 "View All"按钮后如何显示 RecyclerView 项目