使用来自 JSON 的节点 JS 创建 XML 响应

Creating an XML response using node JS from JSON

我希望从对象中的数组创建一个 XML 模式。数组的长度各不相同,基于此我想创建一个生成响应的逻辑。下面是格式和例子。

Object - Exact

 "Data": [{
            "JK": true,
            "Number": "02154029",
            "Name": "Allen",
            "Type": "Delta",
            "Code": "ASM",
            "Amount": 10

        },
        {
            "JK": true,
            "Number": "92154429",
            "Name": "Peter",
            "Type": "Delta",
            "Code": "FLSM",
            "Amount": 50

        },
.
.
.
.
"n items"
]

上面是改变长度的对象,使用上面的对象我想创建下面的 XML 模式。

XML - Expected

<request ...........>
  <delta.....>
    <lineItem id = 1....>
    </lineItem>
    <lineItem id = 2....>
    </lineItem>
    .
    .
    .
    <lineItem id = n....>(based on length of above array)
    </lineItem>
    <params amount = "10" code = "ASM" batch = "1">
    <params amount = "50" code = "FLSM" batch = "2">
    .
    .
    .
    .
    <params amount = n code = n batch = n>(based on length of above array)
 </delta>
 <keys number = "02154029" name = "Allen">
 <keys number= "92154429" name = "Peter">
 .
 .
 .
 <keys number= n name = n >(based on length of above array)
</request>

我请求你帮助我解决这个问题,方法是使用 Javascript

创建一个逻辑

如有任何疑问,请告诉我

考虑到您的预期输出,它有点复杂,但可以使用模板、json 解析器、DOMParser 和 querySelector:

 tmpl = `<doc>
    <request>
         <delta>         
         </delta>         
         </request>
</doc>`

const data = `[{
            "JK": true,
            "Number": "02154029",
            "Name": "Allen",
            "Type": "Delta",
            "Code": "ASM",
            "Amount": 10

        },
        {
            "JK": true,
            "Number": "92154429",
            "Name": "Peter",
            "Type": "Delta",
            "Code": "FLSM",
            "Amount": 50

        }

]`
const jdata = JSON.parse(data);
const xmldoc = new DOMParser().parseFromString(
    tmpl,
    'text/xml'
  );
dest = xmldoc.querySelector('delta')

counter = 1;
for (let jd of jdata){
dest.insertAdjacentHTML(
      'beforeend',
      `<lineItem id = "${counter}"> </lineItem>
      `
    );
counter++;
}

for (let jd of jdata){
dest.insertAdjacentHTML(
      'beforeend',
      `<params amount = "${jd.Amount}" code = "${jd.Code}"> </params>
      
      `
    );
}
for (let jd of jdata){
dest.insertAdjacentHTML(
      'afterend',
      `
      <keys number = "${jd.Number}" name = "${jd.Name}"> </keys>
      `
    );
}


alert(xmldoc.documentElement.innerHTML)