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

使用xmlbuilder2创建XML时,如何在CDATA段中插入XML节点?

使用xmlbuilder2生成含CDATA段XML的问题解决

问题

使用xmlbuilder2创建包含CDATA段的XML文档时,XmlRequest节点的CDATA内容被错误渲染为[object Object],无法生成预期的XML节点内容。

现有代码

const xmlObj = {
    "s:Envelope": {
        '@xmlns:s': "http://schemas.xmlsoap.org/soap/envelope/",
         "s:Body": {
            "DoStuff": {
                '@xmlns': "https://randomUrl",
                'XmlRequest': {
                    '$': {
                         'test': 'apples'
                     }                                                                
                 }
             }
          }
        }
    }
    
const final = xmlBuilder.create(xmlObj).end({ prettyPrint: true});    

return final;    

当前错误输出

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <DoStuff xmlns="https://randomUrl">
      <XmlRequest><![CDATA[[object Object]]]></XmlRequest>
    </DoStuff>
  </s:Body>
</s:Envelope>

期望输出

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <DoStuff xmlns="https://randomUrl">
      <XmlRequest>
         <![CDATA[<test>
           apples
         </test>]]>
      </XmlRequest>
    </DoStuff>
  </s:Body>
</s:Envelope>

解决方案

问题出在直接将对象传入CDATA的$属性中,xmlbuilder2会将对象转为字符串[object Object]。正确做法是先单独生成CDATA内部的XML结构,再将其作为字符串传入$。

修改后的代码:

// 先生成CDATA内部的XML字符串
const cdataContent = xmlBuilder.create({ test: 'apples' }).end({ prettyPrint: true });

const xmlObj = {
    "s:Envelope": {
        '@xmlns:s': "http://schemas.xmlsoap.org/soap/envelope/",
         "s:Body": {
            "DoStuff": {
                '@xmlns': "https://randomUrl",
                'XmlRequest': {
                    '$': cdataContent                                                                
                 }
             }
          }
        }
    }
    
const final = xmlBuilder.create(xmlObj).end({ prettyPrint: true });    

return final;    

这样就能生成包含正确XML节点的CDATA段,符合预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:03:49