Django的。如何在上传期间解析xml文件

时间:2018-04-17 17:21:47

标签: xml django xml-parsing django-forms django-views

我的观点

class TestFilesView(FormView):
    form_class = TestFilesForm
    template_name = 'testy/xml_files_upload.html'

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file_field')
        if form.is_valid():
            for f in files:
                instance = TestFiles(
                    id_test=TestHeader(self.kwargs['id']),
                    name='xx',
                    file_name=f.name,
                    file_field=f
                )
                instance.save()

            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def get_success_url(self):
        return reverse('tests_list')

如何打开上传xml文件,从xml文件中获取“name”属性并将其转发到我的istance名称变量?

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

您应该使用像Beautiful Soup这样的解析库。您可以尝试以下内容:

if form.is_valid():
            for f in files:
                instance = TestFiles(
                    id_test=TestHeader(self.kwargs['id']),
                    name='xx',
                    file_name=f.name,
                    file_field=f
                )
                instance.save()
                with open(f.read(), 'r') as file:
                    soup = BeautifulSoup(file, 'xml.parser')
                    instance.name = soup.name
                    instance.save()