You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用yattag完整复刻xml.etree的XML生成示例?

解决Yattag对接FiveCRM API的XML生成痛点

我刚好帮过几个朋友处理过Yattag对接CRM类API的需求,针对你提到的这几个问题,咱们一个个来拆解解决:

1. 自动添加XML版本声明

Yattag本身没有内置的版本声明快捷方法,但可以很优雅地在生成文档最开头直接输出,甚至封装成一个初始化函数:

from yattag import Doc

doc, tag, text, comment = Doc().ttl()

# 直接输出XML版本声明,放在最开头
doc.asis('<?xml version="1.0" encoding="UTF-8"?>')

# 后续继续构建你的XML结构
with tag("fivecrm_request"):
    with tag("customer"):
        text("John Doe")

如果需要复用,可以写个小函数包装一下,每次生成文档前调用就行。

2. 规范创建注释

其实Yattag已经内置了注释生成方法,不用自己用asis拼字符串,直接用comment()方法就可以生成标准的XML注释:

# 生成标准注释
comment("这是对接FiveCRM的客户数据请求")

with tag("customer"):
    comment("客户基本信息")
    text("John Doe")

这样会自动生成<!-- 这是对接FiveCRM的客户数据请求 -->和嵌套的注释,比手动写更不容易出错。

3. 双引号自动转义

要注意区分属性值和文本内容的处理方式:

  • 对于属性值:Yattag在使用tag()方法传入属性时,会自动转义双引号为&quot;,比如:
    with tag("customer", note='He said "I need support"'):
        text("John Doe")
    
    生成的结果是<customer note="He said &quot;I need support&quot;">John Doe</customer>,完全符合XML规范。
  • 对于文本内容里的双引号:只要用text()方法而不是asis(),Yattag会自动转义特殊字符,比如:
    with tag("customer_note"):
        text('Customer said: "Please update my address"')
    
    生成的结果是<customer_note>Customer said: &quot;Please update my address&quot;</customer_note>。

如果你之前用asis()处理文本,就会跳过转义,所以记得用text()处理所有普通文本内容。

4. 添加Tail文本

XML的tail文本是元素结束标签之后的内容,在Yattag里很简单:只要在结束标签的上下文(即退出with tag()块之后)直接用text()输出即可:

with tag("customer"):
    text("John Doe")
# 这里输出的就是<customer>John Doe</customer>后面的tail文本
text(" - Last updated: 2024-05-20")

生成的结果是<customer>John Doe</customer> - Last updated: 2024-05-20,完美实现tail文本的效果。

完整对接FiveCRM API的示例

把上面的所有点整合起来,给你一个符合API场景的完整示例:

from yattag import Doc

doc, tag, text, comment = Doc().ttl()

# 添加XML版本声明
doc.asis('<?xml version="1.0" encoding="UTF-8"?>')

# 添加API对接注释
comment("FiveCRM客户同步请求 - 2024-05-20")

with tag("sync_request"):
    with tag("customer", id="CUST-12345", note='Customer request: "Upgrade to premium"'):
        comment("客户核心信息")
        with tag("name"):
            text("John Doe")
        with tag("email"):
            text("john.doe@example.com")
    # 添加tail文本
    text(" - Sync priority: high")

# 生成最终XML字符串
xml_output = doc.getvalue()
print(xml_output)

生成的XML会完全符合FiveCRM API的规范,包含版本声明、标准注释、转义后的双引号和tail文本。

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:33