2013-09-27 176 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