gpt4 book ai didi

python - 如何更改根元素和列表项元素的名称? (django-rest-框架)

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:33 27 4
gpt4 key购买 nike

我是 django-rest-framework 的新手,我有类似的工作示例

<root>
<list-item>worrier1</list-item>
<list-item>worrier2</list-item>
<root>

我需要的是

<Hero>
<worrier1>worrier1</worrier1>
<worrier2>worrier2</worrier2>
<Hero>

最佳答案

本着对搜索此内容的任何其他人有所帮助的精神...下面是如何将 XMLRenderer 子类化并覆盖根标记(以前是“root”)和项目标记(以前是“list-item”)以随心所欲。

from django.utils.six.moves import StringIO
from django.utils.xmlutils import SimplerXMLGenerator
from rest_framework_xml.renderers import XMLRenderer

class ModifiedXMLRenderer(XMLRenderer):
item_tag_name = "item"
root_tag_name = "channel"

def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders `data` into serialized XML.
"""
if data is None:
return ''

stream = StringIO()

xml = SimplerXMLGenerator(stream, self.charset)
xml.startDocument()
xml.startElement(self.root_tag_name, {})

self._to_xml(xml, data)

xml.endElement(self.root_tag_name)
xml.endDocument()
return stream.getvalue()

def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement(self.item_tag_name, {})
self._to_xml(xml, item)
xml.endElement(self.item_tag_name)

elif isinstance(data, dict):
for key, value in six.iteritems(data):
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)

elif data is None:
# Don't output any value
pass

else:
xml.characters(smart_text(data))

关于python - 如何更改根元素和列表项元素的名称? (django-rest-框架),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com