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

SAP CPI使用Groovy脚本添加XML节点报错问题求助

SAP CPI Groovy脚本为XML新增节点解决方案

问题原因

  • 报错No signature of method: groovy.util.NodeList.appendNode():root.Line返回的是NodeList集合类型,部分Groovy运行环境中即使通过下标[0]取值,也可能没有正确解析为单个Node对象,而appendNode是Node类的专属方法,用NodeList调用就会抛出方法不存在的错误。
  • 输出与输入完全一致:仅修改了内存中的XML节点对象,没有将修改后的节点树序列化后重新写入消息体,SAP CPI最终返回的还是原始输入内容。

正确实现代码

import com.sap.gateway.ip.core.customdev.util.Message
import groovy.xml.XmlParser
import groovy.xml.XmlUtil

def Message processData(Message message) {
    // 读取原始消息体
    def body = message.getBody(java.lang.String) as String
    def root = new XmlParser().parseText(body)
    
    // 明确获取第一个Line节点,新增Field5节点
    def targetLine = root.Line.first()
    targetLine.appendNode("Field5", [:], "MyNewField")
    
    // 将修改后的XML序列化后写回消息体
    String modifiedXml = XmlUtil.serialize(root)
    message.setBody(modifiedXml)
    
    return message
}

输出结果样例

<?xml version="1.0" encoding="UTF-8"?>
<Records>
  <Line>
    <Field1>ABC</Field1>
    <Field2>123</Field2>
    <Field3>XXX</Field3>
    <Field4>567890</Field4>
    <Field5>MyNewField</Field5>
  </Line>
</Records>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 11:45:03