gpt4 book ai didi

python - 如何使用 XMLGenerator 生成空的封闭元素?

转载 作者:行者123 更新时间:2023-11-30 23:47:15 27 4
gpt4 key购买 nike

在 Django 中,

addQuickElement(name,content,attr)

生成这样的XML

<name attr="attr">content</name>

虽然我想生成

<name attr="attr" />

最佳答案

只是不要指定 contents 参数。

作为引用,这是django/utils/xmlutils.py:

"""
Utilities for XML generation/parsing.
"""

from xml.sax.saxutils import XMLGenerator

class SimplerXMLGenerator(XMLGenerator):
def addQuickElement(self, name, contents=None, attrs=None):
"Convenience method for adding an element with no children"
if attrs is None: attrs = {}
self.startElement(name, attrs)
if contents is not None:
self.characters(contents)
self.endElement(name)

您可以在这里看到,您只需要不指定contents,因此您可以执行x.addQuickElement(name, attrs=attrs)

(快速查看 XMLGenerator 表明这仍会生成结束标记,而不是自结束标记。在 Python 3.2 中,参数 short_empty_elements 已添加到 XMLGenerator.__init__,但 Django 仍然不仅仅与 Python 2.x 兼容。如果您关心获得短标记,请查看 xml.sax.saxutils.XMLGenerator.startElement 实现。)

关于python - 如何使用 XMLGenerator 生成空的封闭元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8455704/

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