沉思 recently asked question ,我开始怀疑是否有一种非常简单的方法可以在 Python 中处理 XML 文档。如果你愿意的话,这是一种 Python 的方式。
如果我举个例子,也许我能解释得最好:让我们说以下内容——我认为这是一个很好的例子,说明 XML 在 Web 服务中是如何(错误)使用的——是我从 http 请求得到的响应 http://www.google.com/ig/api?weather=94043
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<forecast_information>
<city data="Mountain View, CA"/>
<postal_code data="94043"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2010-06-23"/>
<current_date_time data="2010-06-24 00:02:54 +0000"/>
<unit_system data="US"/>
</forecast_information>
<current_conditions>
<condition data="Sunny"/>
<temp_f data="68"/>
<temp_c data="20"/>
<humidity data="Humidity: 61%"/>
<icon data="/ig/images/weather/sunny.gif"/>
<wind_condition data="Wind: NW at 19 mph"/>
</current_conditions>
...
<forecast_conditions>
<day_of_week data="Sat"/>
<low data="59"/>
<high data="75"/>
<icon data="/ig/images/weather/partly_cloudy.gif"/>
<condition data="Partly Cloudy"/>
</forecast_conditions>
</weather>
</xml_api_reply>
在加载/解析此类文档后,我希望能够像这样简单地访问信息
>>> xml['xml_api_reply']['weather']['forecast_information']['city'].data
'Mountain View, CA'
或
>>> xml.xml_api_reply.weather.current_conditions.temp_f['data']
'68'
从我目前看到的情况来看,似乎 ElementTree
是最接近我梦想的。但它不存在,在使用 XML 时仍有一些摸索要做。 OTOH,我的想法并没有那么复杂——可能只是解析器顶部的薄薄的一层——但它可以减少处理 XML 的烦恼。有这样的魔法吗? (如果不是 - 为什么?)
PS。注意我试过BeautifulSoup
已经,虽然我喜欢它的方法,但它确实存在空 <element/>
的问题s - 请参阅下面的评论中的示例。
最佳答案
已经提到了lxml。您还可以查看 lxml.objectify进行一些非常简单的操作。
>>> from lxml import objectify
>>> tree = objectify.fromstring(your_xml)
>>> tree.weather.attrib["module_id"]
'0'
>>> tree.weather.forecast_information.city.attrib["data"]
'Mountain View, CA'
>>> tree.weather.forecast_information.postal_code.attrib["data"]
'94043'
关于python - 在 Python 中处理 XML 真的很简单吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106480/