0

我正在尝试使用 ElementTree 解析 XML,但出现此错误:

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

我的文件.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 时。有谁知道如何解决这种问题?

4

2 回答 2

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)
于 2013-09-27T19:05:12.137 回答
0

虽然您不能确定文件应该采用何种编码,但我尝试将 xml 编码声明更改为 utf-8 并且 ElementTree 能够解析它。

weather = client.service.GetWeather('Sao Paulo', 'Brazil')
weather = weather.replace('encoding="utf-16"?', 'encoding="utf-8"?')
于 2013-09-27T19:03:23.340 回答