爲了彌補recently asked question,我開始懷疑是否有一種非常簡單的方式來處理Python中的XML文檔。一種pythonic方式,如果你願意的話。在Python中處理XML的真正簡單的方法是什麼?
也許我可以解釋的最好的,如果我給例子:假設如下 - 我認爲這是的XML是如何在Web服務中使用(MIS)一個很好的例子 - 在響應我從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存在實際問題 - 請參閱下面的示例註釋。
ElementTree可能是最好的,而不依賴於第三方庫。 – carl 2010-06-24 00:27:57
我認爲lxml.objectify是這個問題的完美解決方案。 – shahjapan 2010-06-24 02:56:35
你正在尋找的東西看起來很像Perl的XML :: Simple CPAN模塊,它很適合很多常規的XML工作。有人感到勤奮可能可以實現類似於etree wrapper的東西。 – 2010-06-24 04:56:15