Node.js Lambda函数中xml2js构建指定XML结构失败问题排查
Node.js Lambda中用xml2js生成目标XML的正确实现
目标XML输出:
<Section ProductId="46m8t"> <Item ItemQty="1"> <Image>Road.jpg</Image> <ItemProductValue>0.50</ItemProductValue> <ItemShippingValue>1.00</ItemShippingValue> </Item> </Section>
完整Lambda函数代码
const xml2js = require('xml2js'); exports.handler = async (event) => { // 构建与目标XML结构匹配的JavaScript对象 const xmlData = { Section: { $: { ProductId: "46m8t" }, // 元素属性通过$对象定义 Item: { $: { ItemQty: "1" }, Image: "Road.jpg", ItemProductValue: "0.50", ItemShippingValue: "1.00" } } }; // 配置xml2js Builder参数 const builder = new xml2js.Builder({ headless: true, // 不生成XML声明头(如需声明可移除该参数) renderOpts: { pretty: true, // 开启格式化输出 indent: ' ', // 匹配目标XML的缩进(8个空格) newline: '\n' } }); try { // 生成XML字符串 const xml = builder.buildObject(xmlData); return { statusCode: 200, body: xml }; } catch (error) { console.error('XML构建失败:', error); return { statusCode: 500, body: 'XML生成失败' }; } };
关键配置说明
- 元素属性定义:xml2js要求用
$对象声明元素的属性,比如<Section ProductId="46m8t">对应对象内的$: { ProductId: "46m8t" },这是最容易出错的点,直接把属性放在外层会导致结构错误。 - 格式化配置:
renderOpts里的pretty设为true开启格式化,indent设置为目标XML对应的空格数,确保输出格式完全匹配需求。 - headless参数:如果不需要XML声明头(
<?xml version="1.0" encoding="UTF-8"?>),就保留headless: true;如果需要声明头,直接移除该参数即可,默认会生成标准声明。
内容的提问来源于stack exchange,提问作者Patrick Collet
相关产品推荐
相关产品推荐

