簡體   English   中英

用元素樹解析XML

[英]Parsing XML with element tree

我正在嘗試使用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時。 有人知道如何解決這種問題嗎?

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)

雖然你不能確定編碼文件應該是的,我試圖改變XML編碼聲明為UTF-8和ElementTree的是能夠解析它。

weather = client.service.GetWeather('Sao Paulo', 'Brazil')
weather = weather.replace('encoding="utf-16"?', 'encoding="utf-8"?')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM