繁体   English   中英

在Python中解析XML Pastebin响应

[英]Parsing XML Pastebin response, in Python

我正在尝试通过他们的API在Pastebin上进行搜索。 我正在使用pastebin库搜索python。

问题是我收到一个具有重复键的XML响应。

这是回应

<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>

所以我试图解析它返回paste_keypaste_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

退货

    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 {}

编辑 :所以我应该使用elem.text,所以这是现在的工作,但主要的问题依然存在:我怎样才能返回元素,其中paste_keypaste_title == goodPaste

编辑2中奖彩票:

result = xml.findall(".//paste[paste_title='goodPaste']/paste_key")
print result[0].text

您可以为此使用XPath:

result = xml.findall(".//paste[paste_title='goodPaste']/paste_key")
print result.text

这应该在您的情况下打印fsfgdsgg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM