2017-03-09 44 views
0

嗨我想创建一个xml文档,其中包含一些法语字母表的内容。我修改过的xml标签(通过脚本)在新的xml文件(我创建的那个文件)中有正确的输出,但所有没有修改的xml标签都有一些意想不到的字符。BeautifulSoup如何使用utf-8编写XML文件

#Open file 
soup = BeautifulSoup(open('example2.xml'),'xml') 

#... 
# code that update (modify) some xml element value 
#.... 

#write to a file 
def create_a_file(content, filename = 'hello.xml'): 
    f = open(filename, "w") 
    f.write(str(content)) 
    f.close() 


#.. output of the file 
# I modify this tag with a script and it displays well 
<subTitl>Enquête sur le web, juillet 2010</subTitl> 
# I didn't modify either the tag or the attribute but it doesn't display properly 
<AuthEnty university="Université Montpellier. Centre géographique, statistique"> 
      ésir, Pras 
     </AuthEnty> 

正如您所看到的,我没有修改名为AuthEnty的XML元素,但我有一些意外的字符。

问题 我该如何正确编写此文档。它是开放的,该文件没有正确解析?

回答

0

导入编解码器的作品。

#Open file 
import codecs 
f = codecs.open('example2.xml','r','utf-8') 
soup = BeautifulSoup(f.read(),"xml") 
f.close() 

这会显示正确的输出,当我写入创建一个XML文件。