minidom解析非UTF-8编码的xml文件
Python中使用minidom解析xml,会遇到编码问题。minidom支持UTF-8的编码,对于其他的编码,必须进行转换,否则解析时会产生异常。下面以读取gb2312编码的xml文件为例。
sourceFile = codecs.open(sourceFilePath,mode='r')
xmlContentStr = sourceFile.read()
xmlContentStr = xmlContentStr.decode('gb2312').encode('utf-8')
xmlContentStr =xmlContentStr.replace('encoding="gb2312"','encoding="utf-8"')
sourceXML = minidom.parseString(xmlContentStr)