使用带有错误标记的Python ElementTree解析XML

时间:2013-08-15 00:55:24

标签: python xml parsing xml-parsing

我正在尝试使用Python来解析XML文件,以便从XML Feed中获取标题,作者,URL和摘要。然后我确保我们收集数据的XML就像这样:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
  xmlns:grddl="http://www.w3.org/2003/g/data-view#"
  grddl:transformation="2turtle_xslt-1.0.xsl">

<title>Our Site RSS</title>
<link href="http://www.oursite.com" />
<updated>2013-08-14T20:05:08-04:00</updated>
<id>urn:uuid:c60d7202-9a58-46a6-9fca-f804s879f5ebc</id>
<rights>
    Original content available for non-commercial use under a Creative
    Commons license (Attribution-NonCommercial-NoDerivs 3.0 Unported),
    except where noted.
</rights>

<entry>
    <title>Headline #1</title>
    <author>
        <name>John Smith</name>
    </author>
    <link rel="alternate"
          href="http://www.oursite.com/our-slug/" />
    <id>1234</id>
    <updated>2013-08-13T23:45:43-04:00</updated>

    <summary type="html">
        Here is a summary of our story
    </summary>
</entry>
<entry>
    <title>Headline #2</title>
    <author>
        <name>John Smith</name>
    </author>
    <link rel="alternate"
          href="http://www.oursite.com/our-slug-2/" />
    <id>1235</id>
    <updated>2013-08-13T23:45:43-04:00</updated>

    <summary type="html">
        Here is a summary of our second story
    </summary>
</entry>

我的代码是:

import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()

for child in root:
    print child.tag

当Python打印child.tag时,标签不是标签“entry”,而是“{http://www.w3.org/2005/Atom}条目”。我试过用:

for entry in root.findall('entry'):

但是这不起作用,因为条目标记包含作为根标记一部分的w3 url。此外,让root的孙子们将其标记显示为“{http://www.w3.org/2005/Atom}作者”

我无法更改XML,但是如何修改它(将root设置为)并重新保存或更改我的代码以便root.findall('entry')有效?

2 个答案:

答案 0 :(得分:5)

这是标准的ElementTree行为。如果您要搜索的标记是在命名空间中声明的,则在搜索这些标记时必须指定该命名空间。但是,您可以这样做:

import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()

def prepend_ns(s):
    return '{http://www.w3.org/2005/Atom}' + s

for entry in root.findall(prepend_ns('entry')):
    print 'Entry:'
    print '    Title: '   + entry.find(prepend_ns('title')).text
    print '    Author: '  + entry.find(prepend_ns('author')).find(prepend_ns('name')).text
    print '    URL: '     + entry.find(prepend_ns('link')).attrib['href']
    print '    Summary: ' + entry.find(prepend_ns('summary')).text

答案 1 :(得分:1)

尝试使用BeautifulSoup4,它不仅非常强大,不仅可以解析XML,还可以解析HTML等。 这是一个转发代码,希望可以提供帮助。

from bs4 import BeautifulSoup

def main():
    input = """....""" 
    soup = BeautifulSoup(input)   
    for entry in soup.findAll("entry"):
        title = entry.find("title").text.strip()
        author = entry.find("author").text.strip()
        link  = entry.find("link").text.strip()
        summary = entry.find("summary").text.strip()
        print title, author, link, summary
if __name__ == '__main__':
    main()