【问题标题】:Django REST XMLParser() - cannot parse item listDjango REST XMLParser() - 无法解析项目列表
【发布时间】:2023-03-29 00:50:01
【问题描述】:

我正在尝试使用 Django REST XMLParser 解析项目列表。解析器将项目列表视为单个项目。这是 XML:

XML = """<?xml version="1.0" encoding="UTF-8"?>
                <root>
                <item>
                    <ID>item_1</ID>
                    <Description>first item</Description>
                </item>
                <item>
                    <ID>item_2</ID>
                    <Description>second item</Description>
                </item>
                </root>
            """

这里是解析器:

from django.conf import settings    
settings.configure()
from django.utils.six import BytesIO
from rest_framework_xml.parsers import XMLParser

data_stream = BytesIO(XML)
parsed_data = XMLParser().parse(data_stream)

print parsed_data

这将返回以下 json:

{'item': {'ID': 'item_2', 'Description': 'second item'}}

所以看起来 XMLParser() 正在覆盖列表项 1,并返回列表项 2。从上面的代码中,我期望:

[{'item': {'ID': 'item_1', 'Description': 'first item'}}, {'item': {'ID': 'item_2', 'Description': 'second item'}}]

【问题讨论】:

标签: python django xml-parsing django-rest-framework


【解决方案1】:

从源码来看,我觉得你需要把&lt;item&gt;改成&lt;list-item&gt;。标签名称似乎是硬编码的:

https://github.com/jpadilla/django-rest-framework-xml/blob/master/rest_framework_xml/parsers.py#L51

更新以回应您的评论:

由 DRF 完成的 xml 解析/渲染是序列化的一部分。它可能并不意味着 OXM(对象-XML 映射)。看看https://github.com/jpadilla/django-rest-framework-xml/blob/master/rest_framework_xml/renderers.py#L21 - 你应该使用渲染器来创建你以后用解析器解析的xml。

警告:我没有使用 DRF 的 XML 部分,我只是在阅读它的代码。

【讨论】:

  • 如果为真,这是代表 django-rest-framework-xml 对于我的应用程序(解析 b2mml XML)的一个巨大假设,“item”标签是 并且有很多其他不使用名为“list-item”的标签的应用程序。
猜你喜欢
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多