Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python解析XML文件,同时提取属性和子项_Python_Xml - Fatal编程技术网

使用Python解析XML文件,同时提取属性和子项

使用Python解析XML文件,同时提取属性和子项,python,xml,Python,Xml,我试图用Python读取一个XML文件,其一般格式如下: <item id="1149" num="1" type="topic"> <title>Afghanistan</title> <additionalInfo>Afghanistan</additionalInfo> </item> 然而,每当我运行这段代码时,我都会得到一个错误回溯(最近一次调用last):文件“python”,第9行,在Type

我试图用Python读取一个XML文件,其一般格式如下:

<item id="1149" num="1" type="topic">
    <title>Afghanistan</title>
    <additionalInfo>Afghanistan</additionalInfo>
</item>
然而,每当我运行这段代码时,我都会得到一个错误
回溯(最近一次调用last):文件“python”,第9行,在TypeError:应该是一个字符缓冲区对象
,这让我觉得我没有使用能够处理XML的东西。 是否有任何方法可以将XML文件保存到一个文件中,然后提取每个部分的
标题
,以及与该标题关联的
id
属性?
谢谢你的帮助。

你想要的是
response.read()
而不是
response
。响应变量是一个实例,而不是xml字符串。通过执行
response.read()
它将从响应实例中读取xml

然后可以将其直接写入文件,如下所示:

url = 'http://api.npr.org/list?id=3002' #1007 is science
response = urlopen(url)
f = open('out.xml', 'w')
f.write(response.read())
url = 'http://api.npr.org/list?id=3002' #1007 is science
response = urlopen(url)
tree = ET.fromstring(response.read())
或者,您也可以将其直接解析到ElementTree中,如下所示:

url = 'http://api.npr.org/list?id=3002' #1007 is science
response = urlopen(url)
f = open('out.xml', 'w')
f.write(response.read())
url = 'http://api.npr.org/list?id=3002' #1007 is science
response = urlopen(url)
tree = ET.fromstring(response.read())
要提取所有id/标题对,还可以执行以下操作:

url = 'http://api.npr.org/list?id=3002' #1007 is science
response = urlopen(url)
tree = ET.fromstring(response.read())
for item in tree.findall("item"):
    print item.get("id")
    print item.find("title").text

从那里,您可以决定在何处存储/输出值

您可以通过以下代码读取响应内容:

import urllib2
opener = urllib2.build_opener(urllib2.HTTPRedirectHandler(),urllib2.HTTPCookieProcessor())
response= opener.open("http://api.npr.org/list?id=3002").read()
opener.close()
然后将其写入文件:

f = open('out.xml', 'w')
f.write(response)
f.close()