我有一个 XML 文件test.xml
,内容:
<?xml version='1.0' encoding='UTF-8'?>
<Configurations version="1.0">
<Item name="a" value="avalue" />
<Item name="b" value="bvalue" />
</Configurations>
我想用 Python ElementTree 改变一些属性值。蟒蛇程序是:
#!/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()
当我像这样执行python文件时:Windows命令提示符中的“encode.py测试bvalue”,它以异常结束:
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)
为什么会出现这个错误?我的操作系统是 Windows 7、64 位