【问题标题】:Cannot append the data into xml file using Django and Python无法使用 Django 和 Python 将数据附加到 xml 文件中
【发布时间】:2017-06-15 12:22:50
【问题描述】:

我正在尝试将我所有的帖子数据附加到 xml 文件中,但它总是被覆盖。这是我的代码:

def some(request):
    if request.method == 'POST':
        location_name = request.POST.get('lname')
        rname = request.POST.get('rname')
        seat = request.POST.get('seat')
        projector = request.POST.get('projector')
        video = request.POST.get('video')
        root = ET.Element("roomlist")
        doc = ET.SubElement(root, "locationname", name=location_name)
        doc1 = ET.SubElement(doc, "roomid", name="1234")
        ET.SubElement(doc1, "roomname", name=rname).text = rname
        ET.SubElement(doc1, "noseats", name=seat).text = seat
        ET.SubElement(doc1, "projectorscreen", name=projector).text = projector
        ET.SubElement(doc1, "videoconf", name=video).text = video
        tree = ET.ElementTree(root)
        tree.write("filename.xml")
    return render(request, 'booking/bmr.html', {})

这里我需要当用户提交表单时,所有数据都将附加到现有的 XML 文件中,但在我的情况下,它每次都会被覆盖。

【问题讨论】:

    标签: python xml django


    【解决方案1】:

    您需要创建数据并附加到文件中:

    root = tree.getroot()    
    xmlstr = ET.tostring(root, 'utf-8', method='xml')
    with open("filename.xml", "a") as myfile:
        myfile.write(xmlstr)
    

    所以我要做的是创建树(您的代码)并转换为字符串(tostring()),然后将此字符串附加到文件中 :)

    【讨论】:

    • 我按照你的要求做了,但它抛出了这个 NameError at /some/ global name 'ElementTree' is not defined 错误。
    • 我正在使用这个import xml.etree.cElementTree as ET一个
    • 所以使用ET.fromstring 而不是ElementTree.tostring
    • 我做到了,但它抛出了这个TypeError at /some/ XML() got an unexpected keyword argument 'encoding' 错误。
    • 我已经使用 cElementTree 根据您的需要编辑了我的答案
    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2018-02-22
    相关资源
    最近更新 更多