pydantic_ai.format_as_xml
format_as_xml
format_as_xml(
obj: Any,
root_tag: str = "examples",
item_tag: str = "example",
include_root_tag: bool = True,
none_str: str = "null",
indent: str | None = " ",
) -> str
将 Python 对象格式化为 XML。
这很有用,因为大型语言模型 (LLM) 通常发现读取半结构化数据(例如示例)为 XML 比 JSON 等更容易。
支持:str
, bytes
, bytearray
, bool
, int
, float
, date
, datetime
, Mapping
, Iterable
, dataclass
, 和 BaseModel
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
obj
|
Any
|
要序列化为 XML 的 Python 对象。 |
必需 |
root_tag
|
str
|
用于包裹 XML 的外部标签,使用 |
'examples'
|
item_tag
|
str
|
用于可迭代对象(例如列表)中每个项目的标签,对于数据类和 Pydantic 模型,此标签将被类名覆盖。 |
'example'
|
include_root_tag
|
bool
|
是否在输出中包含根标签(如果根标签包含主体,则始终包含根标签 - 例如,当输入是简单值时)。 |
True
|
none_str
|
str
|
用于 |
'null'
|
indent
|
str | None
|
用于美化打印的缩进字符串。 |
' '
|
返回值
类型 | 描述 |
---|---|
str
|
对象的 XML 表示形式。 |
示例
format_as_xml_example.py
from pydantic_ai.format_as_xml import format_as_xml
print(format_as_xml({'name': 'John', 'height': 6, 'weight': 200}, root_tag='user'))
'''
<user>
<name>John</name>
<height>6</height>
<weight>200</weight>
</user>
'''
pydantic_ai_slim/pydantic_ai/format_as_xml.py
中的源代码
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
|