Python ElementTree write xml file with chinese,has error
"UnicodeDecodeError : 'ascii' codec can't decode byte"
everyone,I have a problem in ElementTree.
I have a xml file, name is "test.xml", the content are:
<?xml version='1.0' encoding='UTF-8'?>
<Configurations version="1.0">
<Item name="a" value="avalue" />
<Item name="b" value="bvalue" />
</Configurations>
And I want to change the value by python ElementTree. The python file's
content are:
#!/usr/bin/python
#coding=utf-8
###############################################################################
import sys
from xml.etree import ElementTree as ET
a_value = ""
b_value = ""
# Functions to modify the Upgrader configuration files.
def Modify_Config ():
tree = ET.parse('./test.xml')
root = tree.getroot()
for child in root.getiterator():
childName = child.get('name')
if 'a' == childName:
child.set('value', a_value)
elif 'b' == childName:
child.set('value', b_value)
tree.write('./test.xml', encoding="UTF-8")
###############################################################################
a_value = sys.argv[1]
b_value = sys.argv[2]
###############################################################################
Modify_Config()
when I execute the python file like this: "encode.py ²âÊÔ bvalue" in
windows cmd,It will has error:
D:\Test_study\python\encode>encode.py ²âÊÔ bvalue
Traceback (most recent call last):
File "D:\Test_study\python\encode\encode.py", line 25, in <module>
Modify_Config()
File "D:\Test_study\python\encode\encode.py", line 20, in Modify_Config
tree.write('./test.xml', encoding="UTF-8")
File "C:\Python27\lib\xml\etree\ElementTree.py", line 821, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 940, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 933, in _serialize_xml
v = _escape_attrib(v, encoding)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1091, in _escape_attrib
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb2 in position 0:
ordinal
not in range(128)
So, Could someone tell me the reason,thanks.
No comments:
Post a Comment