我有一个罕见的问题,似乎无法解决,这与在Python中使用ElementTree进行XML解析有关。
尝试搜索有关类似问题的线索和答案,但无济于事
我的功能:
def errorChecker(xmlResponse):
xmlResponse = str(xmlResponse)
xmlText = xmlParser.fromstring(xmlResponse)
errorText = ""
for xmlData in xmlText.iter():
print xmlData.tag
if xmlData.tag == "fault":
for errorData in xmlText.iter('code'):
#errorText = errorDict[errorData]
return errorData.text
return False
当我传递此XML代码时,它返回的效果很好:
"""<?xml version="1.0" encoding="utf-8"?>
<response>
<fault>
<code>1055</code>
</fault>
</response>"""
但是当我直接从服务器获取XML并将其传递给函数时,会出现此错误:
Traceback (most recent call last):
File "wmsTest.py", line 556, in <module>
errorChecker(str(location))
File "wmsTest.py", line 134, in errorChecker
xmlText = xmlParser.fromstring(str(xmlResponse))
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in XML
parser.feed(text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1659, in feed
self._raiseerror(v)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1523, in _raiseerror
raise err
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 6, column 11
添加了有关我的服务器请求的信息:
我使用请求来访问服务器。通过使用:
response = requests.post(appServer, data=xml)
print "raw from server"
print response.text
print "str response"
print str(response.text)
return response.text
响应为:
raw from server
<?xml version="1.0" encoding="utf-8"?>
<response>
<fault>
<code>1055</code>
</fault>
</response>
str response
<?xml version="1.0" encoding="utf-8"?>
<response>
<fault>
<code>1055</code>
</fault>
</response>
Python将传入的XML解释为unicode类型,它与上面的手册XML代码完全一样,因为它是打印件,我只在开头和结尾添加“”。
有任何线索吗?
答案 0 :(得分:1)
对返回的长度进行了一些检查之后,我发现服务器返回的响应比预期的要长,在末尾添加了一个空格。删除空间可以解决问题!