I am using xmlBuilder library in Nodejs to create XML from prepared corresponding JSON.
I am creating JSON structure first and then convert it to XML. Javascript is the coding language.
It is required to create following XML structure.
<A>TestA</A>
<B>TestB</B>
<C>TestC1</C>
<C>TestC2</C>
<D>TestD</D>
Because of the repeated tags (tag C), I am unable to do it. Kindly suggest solutions!
{
A: TestA,
B: TestB,
C: // unclear here
D: TestD
}
In XSLT 3.0 (for example with Saxon-JS) you could transform this JSON:
{
"A": "TestA",
"B": "TestB",
"C": ["TestC1", "TestC2"]
"D": "TestD"
}
to this XML:
<doc>
<A>TestA</A>
<B>TestA</B>
<C>TestA</C>
<C>TestA</C>
<D>TestA</D>
</doc>
with the logic:
<xsl:transform
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:map="http://www.w3.org/2005/xpath-functions.map"
version="3.0"
expand-text="yes">
<xsl:template name="xsl:initial-template">
<doc>
<xsl:variable name="json" select="parse-json('my-input.json')"/>
<xsl:for-each select="sort(map:keys($json))">
<xsl:element name="{.}">{$json(.)}</xsl:element>
</xsl:for-each>
</doc>
</xsl:template>
</xsl:transform>
It's a little more work to transform between JSON and XML using XSLT 3.0 than with some conversion libraries, but the advantage is it gives you total control over the output.