Python xml字符串操作 - 添加标签

时间:2012-09-02 21:52:08

标签: python xml django string xml-parsing

我正在为xml文件进行字符串操作。我用我的查询循环接收的字符串打开文件做我的操作然后我保存文件。我必须将两个括号(如<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")

1 个答案:

答案 0 :(得分:0)

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