开发者

What's an easy and fast way to put returned XML data into a dict?

I'm trying to take the data returned from:

http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true

Into a dict in a fast and easy way. What's the best开发者_运维问答 way to do this?

Thanks.


Using xml from the standard Python library:

import xml.etree.ElementTree as xee
contents='''\
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Ip>74.125.45.100</Ip>
  <Status>OK</Status>
  <CountryCode>US</CountryCode>
  <CountryName>United States</CountryName>
  <RegionCode>06</RegionCode>
  <RegionName>California</RegionName>
  <City>Mountain View</City>
  <ZipPostalCode>94043</ZipPostalCode>
  <Latitude>37.4192</Latitude>
  <Longitude>-122.057</Longitude>
  <TimezoneName>America/Los_Angeles</TimezoneName>
  <Gmtoffset>-25200</Gmtoffset>
  <Isdst>1</Isdst>
</Response>'''

doc=xee.fromstring(contents)
print dict(((elt.tag,elt.text) for elt in doc))

Or using lxml:

import lxml.etree
import urllib2
url='http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true'
doc = lxml.etree.parse( urllib2.urlopen(url) ).getroot()
print dict(((elt.tag,elt.text) for elt in doc))


I would use the xml.dom builtin, something like this:

import urllib
from xml.dom import minidom

data = urllib.urlopen('http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true')
xml_data = minidom.parse(data)
my_dict ={}
for node in xml_data.getElementsByTagName('Response')[0].childNodes:
    if node.nodeType != minidom.Node.TEXT_NODE:
        my_dict[node.nodeName] = node.childNodes[0].data


xml.etree from standard library starting from python2.5. look also at lxml which has the same interface. I don't "dived in" to much but i think that this is also applicable to python >= 2.5 too.

Edit:

This is a fast and really easy way to parse xml, don't really put data to a dict but the api is pretty intuitive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜