Using fast-xml-parser to convert JSON to XML to create list of child nodes

745 views Asked by At

I have the following JSON:

{
    "ExternalId": "1234-01",
    "Name": "product name",
    "Attributes": [
        {
            "Attribute": "attr-value-1"
        },
        {
            "Attribute": "attr-value-2"
        }
    ]
}

and I want to produce the following XML, specifically the Attributes section

<product>
    <ExternalId>1234-01</ExternalId>
    <Name>product name</Name>
    <Attributes>
        <Attribute>attr-value-1</Attribute>
        <Attribute>attr-value-2</Attribute>
    </Attributes>
</product>

I tried few different configuration options but keep getting the below format of the Attributes node (https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/docs/v4/3.XMLBuilder.md)

<product>
    <ExternalId>1234-01</ExternalId>
    <Name>product name</Name>
    <Attributes>
        <Attribute>attr-value-1</Attribute>
    </Attributes>
    <Attributes>
        <Attribute>attr-value-2</Attribute>
    </Attributes>
</product>

Is there any undocumented option to force the desired XML output or does the JSON need to be in different format?

1

There are 1 answers

0
Amit Kumar Gupta On

With the recent version 4.1.4, you can use a property oneListGroup to group all children tags in single parent tag

const builder = new XMLBuilder({oneListGroup:true})
const output = builder.build(json)

Output

<ExternalId>1234-01</ExternalId>
<Name>product name</Name>
<Attributes>
  <Attribute>attr-value-1</Attribute>
  <Attribute>attr-value-2</Attribute>
</Attributes>