0

我正在对 xml 文件进行字符串操作。我打开文件,使用我通过查询 for 循环收到的字符串进行操作,然后保存文件。我必须添加两个括号,例如<document>xml 文件的开头和文件</document>的结尾一次。下面是我的代码。任何想法 ?

def xml(request):
    filename = "/usr/..../...."  
    programs = x.objects.all()
    categories = y.objects.all()

    with open(filename,'r+') as f:  

        old = f.read()
        for m,k in itertools.product(categories,programs):
            if k.name_tr == m.name_tr:
                s = old.replace ('titlesss',k.name_tr,1) 
                j= k.introduction_tr
                decoded = BeautifulStoneSoup(j, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
                x =str(decoded)
                x = unicode(x,"utf-8")
                s = s.replace ("infosss",x,1)
                if  m.id == 310:
                        s = s.replace('idsss',"231",1)
                elif m.id == 308:
                        s = s.replace ('idsss',"230",1)
                elif m.id == 159:
                        s = s.replace ('idsss',"203",1)
                elif m.id == 163:
                        s = s.replace ('idsss',"204",1)
                elif m.id == 280:
                        s = s.replace ('idsss',"212",1)
                elif m.id == 157:
                        s = s.replace ('idsss',"202",1)
                elif m.id == 282:
                        s = s.replace ('idsss',"211",1)
                s = smart_str(s)
                w.write(s)
        return HttpResponseRedirect("asd.xml")
4

1 回答 1

0

我建议您使用etree 模块进行 xml 操作。只需让它解析树,对其进行操作,然后将其写回文件。

于 2012-09-02T22:09:10.683 回答