[英]Parsing XML Pastebin response, in Python
I'm trying to search for something on Pastebin, via their API. 我正在尝试通过他们的API在Pastebin上进行搜索。 I'm searching using the pastebin library for python.
我正在使用pastebin库搜索python。
The problem is that I receive an XML response, that has repeating keys. 问题是我收到一个具有重复键的XML响应。
This is the response 这是回应
<paste>
<paste_key>fadsda</paste_key>
<paste_date>1409074286</paste_date>
<paste_title>badPaste</paste_title>
<paste_size>2040</paste_size>
<paste_expire_date>0</paste_expire_date>
<paste_private>0</paste_private>
<paste_format_long>Bash</paste_format_long>
<paste_format_short>bash</paste_format_short>
<paste_url>http://pastebin.com/url2</paste_url>
<paste_hits>211</paste_hits>
</paste>
<paste>
<paste_key>fsfgdsgg</paste_key>
<paste_date>1398409838</paste_date>
<paste_title>goodPaste</paste_title>
<paste_size>2407</paste_size>
<paste_expire_date>0</paste_expire_date>
<paste_private>2</paste_private>
<paste_format_long>Bash</paste_format_long>
<paste_format_short>bash</paste_format_short>
<paste_url>http://pastebin.com/otherURL</paste_url>
<paste_hits>54</paste_hits>
</paste>
So I am trying to parse it to return paste_key
when paste_title == goodPaste
, but the attrib is always empty 所以我试图解析它返回
paste_key
时paste_title == goodPaste
,但ATTRIB总是空
def parseXML(response):
#I'm adding a root tag
xml = ElementTree.fromstring('<list>' + response + '</list>')
for child in root:
for elem in child:
print elem.tag, elem.attrib
returns 退货
paste_key {}
paste_date {}
paste_title {}
paste_size {}
paste_expire_date {}
paste_private {}
paste_format_long {}
paste_format_short {}
paste_url {}
paste_hits {}
paste_key {}
paste_date {}
paste_title {}
paste_size {}
paste_expire_date {}
paste_private {}
paste_format_long {}
paste_format_short {}
paste_url {}
paste_hits {}
EDIT : So I was supposed to use elem.text, so that's working now, but the main question still exists: How can I return the element where paste_key
when paste_title == goodPaste
编辑 :所以我应该使用elem.text,所以这是现在的工作,但主要的问题依然存在:我怎样才能返回元素,其中
paste_key
时paste_title == goodPaste
EDIT 2 Winning ticket: 编辑2中奖彩票:
result = xml.findall(".//paste[paste_title='goodPaste']/paste_key")
print result[0].text
You can use XPath for that: 您可以为此使用XPath:
result = xml.findall(".//paste[paste_title='goodPaste']/paste_key")
print result.text
This should print fsfgdsgg
in your case 这应该在您的情况下打印
fsfgdsgg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.