使用Python加载XML数据

时间:2012-03-06 18:48:53

标签: python xml

我有这个代码正在运行,但是如何加载项目值而不是对象本身并将其记录到数组中。

import urllib
import xml.etree.ElementTree as xml
tree = xml.parse(urllib.urlopen('http://lazhalazha.livejournal.com/data/rss'))
rootElement = tree.getroot()
for a in rootElement.findall('channel/item/guid'):
    print a

输出

<Element 'guid' at 0xb75316ec>
<Element 'guid' at 0xb7531a0c>
<Element 'guid' at 0xb7531c8c>
<Element 'guid' at 0xb7531f0c>
<Element 'guid' at 0xb753a22c>
<Element 'guid' at 0xb753a4ec>
<Element 'guid' at 0xb753a7ac>
<Element 'guid' at 0xb753aa6c>
<Element 'guid' at 0xb753ad2c>

2 个答案:

答案 0 :(得分:1)

也许你想要a.text

如果guid元素可能包含具有自己文本的子元素,并且您希望对整个文本进行文本序列化,请使用etree.tostring(a, method='text')

这是一个非常基本的问题。仔细阅读Element课程上的lxml tutorial

答案 1 :(得分:0)