2013-09-27 209 views
0

我試圖用ElementTree的解析XML,但我得到這個錯誤:解析XML與元素樹

xml.etree.ElementTree.ParseError: encoding specified in XML declaration is incorrect 

我file.py:

from suds.client import Client 
import xml.etree.ElementTree as ET 

url = 'http://www.webservicex.com/globalweather.asmx?WSDL' 
client = Client(url) 
weather = client.service.GetWeather('Sao Paulo', 'Brazil') 
print weather 

parseWeather = ET.fromstring(weather) # >>>> Here I got my problem! 

當我嘗試解析我的XML從串天氣。任何人都知道如何解決這類問題?

回答

3

weather響應的字符串:

>>> type(weather) 
<class 'suds.sax.text.Text'> 

但ElementTree的會把它變成文字。所要求的編碼然而UTF16:

>>> weather.splitlines()[0] 
'<?xml version="1.0" encoding="utf-16"?>' 

打開這個響應轉換成文本由它明確地編碼到UTF-16:

>>> weather = weather.encode('utf16') 
>>> parseWeather = ET.fromstring(weather) 
0

雖然你不能確定文件的編碼應該是,我試着將xml編碼聲明更改爲utf-8,並且ElementTree能夠解析它。

​​
+0

它看起來replace()方法打開'weather'爲一個字符串。 Martijn有正確的答案。 – Rohmer