Search code examples
jsonxmlxmldocument

Convert JSON list into XML and keep the format


I have a JSON file to convert into XML format with below fields. For "Formats" and "MediaFormats", they are list of integers.

    "Stars": 4.5000000000,
    "Reviews": 11,
    "Formats": [5,6],
    "MediaFormats": [1, 2] 

My expected result is

<Price>29</Price>
<Stars>4.5</Stars>
<Reviews>11</Reviews>
<Formats>5,6</Formats>
<MediaFormats>1,2</MediaFormats>

I tried XmlDocument xmlDoc = JsonConvert.DeserializeXmlNode but the actual result is

<Price>29</Price>
<Stars>4.5</Stars>
<Reviews>11</Reviews>
<Formats>5</Formats>
<Formats>6</Formats>
<MediaFormats>1</MediaFormats>
<MediaFormats>2</MediaFormats>

Any idea how to solve this issue?


Solution

  • Post-process the result with XSLT. No off-the-shelf JSON-to-XML converter (or XML-to-JSON converter) is going to give you the result you want every time; you must be prepared to customise it, and XSLT is the best tool for this.

    You can achieve the required format using

    <xsl:for-each-group select="*" group-adjacent="node-name(.)">
      <xsl:copy>
        <xsl:value-of select="current-group()" separator=","/>
      </xsl:copy>
    </xsl:for-each-group>
    

    Of course, if you're using XSLT anyway, then you could consider using XSLT 3.0's xml-to-json() and json-to-xml() functions so it's all done with one tool.