我正在尝试使用ElementTree解析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时。有谁知道如何解决这类问题?
答案 0 :(得分: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)
答案 1 :(得分:0)
虽然您无法确定文件应的编码,但我尝试将xml编码声明更改为utf-8,并且ElementTree能够解析它。
weather = client.service.GetWeather('Sao Paulo', 'Brazil')
weather = weather.replace('encoding="utf-16"?', 'encoding="utf-8"?')