2017-03-07 99 views
-1

我是新手python用戶,我正在嘗試使用DOM庫更改xml文件中的幾行內容。Python - 使用unicode latin-1修改xml文件的問題

但是我正面臨一個unicode問題來做這個動作。 我的XML文件中有一行

<!--Selector generado a partir del proyecto de configuración : RigelJars_Configuration --> 

看來,該行沒有使用Unicode工作的拉丁-1「(在此引用:configuración)

writer.write("%s<!--%s-->%s" % (indent, self.data, newl)) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 58: ordinal not in range(128) 

下面這個簡單的代碼:

# _*_ coding:utf-8 _*_ 
import os,re,sys 
from xml.dom.minidom import DOMImplementation, Document,parse 
for dirname,subdirs,files in os.walk('/tmp/lab/resource.jar'): 
    for filename in files: 
     if filename == 'variableCfgSelector.xml': 
      domapp=parse('/tmp/lab/resource.jar/variableCfgSelector.xml') 
      print('Arquivo atualmente sendo alterado: variableCfgSelector.xml ') 
      childs = [node for node in domapp.childNodes if node.nodeType == domapp.ELEMENT_NODE] 
      for parent in childs: 
       childs2 = [node for node in parent.childNodes if node.nodeType == domapp.ELEMENT_NODE] 
       for child in childs2: 
        if child.nodeName =='environment': 
         child.firstChild.replaceWholeText('ebanking') 
domapp.writexml(open('/tmp/lab/resource.jar/novo_VariableCfgSelection.xml','w'),addindent='',newl='',encoding='UTF-8') 
domapp.unlink() 
+1

無論是它的Unicode或它的拉丁-1,它是不可能在同一時間。您顯示的複製/粘貼看起來像UTF-8編碼的Unicode,但您使用的軟件配置爲顯示Latin-1。顯示試圖讀取文件的代碼可能有助於澄清這一點,但這幾乎肯定是現有問題的重複 - 您是否搜索過類似的錯誤? – tripleee

+0

另請參閱[Stack Overflow'字符編碼'標記wiki](http://stackoverflow.com/tags/character-encoding/info)瞭解如何提出有關此問題的一些提示。 – tripleee

+1

文件是Latin-1,在這種情況下,您應該在打開時指定此編碼,或者您有雙重編碼的文本,其中已經是UTF-8的文本第二次從Latin-1錯誤地編碼爲UTF-8 。在這種情況下,您可以嘗試撤消轉換並最終生成有效的UTF-8。在不知道文件中的實際字節的情況下,我們只能猜測;但我會把我的賭注放在第一個場景上。 – tripleee

回答

0

我的問題已經修復使用一個簡單的打開的文件(作爲文本文件),而不是使用dom庫的解析。 我的源文件採用ANSI格式進行了統一編碼,使用open可以定義正確的unicode來工作。 感謝所有