python3 env
(1)解析xml报错 ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
from lxml import etree
content = '''<?xml version="1.0"?>
<response version="1.0">
<code>200</code>
<message>Hello</message>
</response>'''
etree.fromstring(content)
Out[12]: <Element response at 0x7f2fad8d4c08>
content = '''<?xml version="1.0" encoding="utf-8"?>
<response version="1.0">
<code>200</code>
<message>Hello</message>
</response>'''
etree.fromstring(content)
---------------------------------------------------------------------------
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
content = b'''<?xml version="1.0" encoding="utf-8"?>
<response version="1.0">
<code>200</code>
<message>Hello</message>
</response>'''
xml = etree.fromstring(content)
print (xml)
Out[5]: <Element response at 0x7f1a1248f288
得到上述的xml的类, 需要转化为string,要加参数encoding='unicode'
etree.tostring(xml)
Out[7]: b'<response version="1.0">\n<code>200</code>\n<message>Hello</message>\n</response>'
etree.tostring(xml, encoding='unicode')
Out[8]: '<response version="1.0">\n<code>200</code>\n<message>Hello</message>\n</response>'
网友评论