简体   繁体   English

将返回的XML数据放入dict是一种简单快捷的方法吗?

[英]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: 使用标准Python库中的xml

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 : 或者使用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: 我会使用xml.dom内置,如下所示:

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. 从python2.5开始的标准库中的xml.etree look also at lxml which has the same interface. 另请参阅具有相同界面的lxml I don't "dived in" to much but i think that this is also applicable to python >= 2.5 too . 我并没有“潜入”,但我认为这也适用于python> = 2.5

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. 这是一种快速且非常简单的解析xml的方法,不是真的把数据放到dict中,但是api非常直观。

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

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