Convert JSON to XML

I use Json.Net to parse JSON for an object and convert to XMLDocument, but I got

InvalidOperationException This document already has a 'DocumentElement' node.

I have JSON data:

{
   "data": [
      {
         "name": "Eros Harem",
         "id": "2345123465"
      },      
      {
         "name": "Vincent Dagpin",
         "id": "56783567245"
      },
      {
         "name": "Vrynxzent Kamote",
         "id": "3456824567"
      }
   ],
   "paging": {
      "next": "nextURLHere"
   }
}

and this is my code

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using Newtonsoft.Json;

namespace JsonToXML
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = File.ReadAllText("friends.json");

            // To convert JSON text contained in string json into an XML node
            XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
        }
    }
}

Am I missing some settings? Any help would be appreciated.

I expect to get something like this as an output.

<?xml version="1.0"?>
<friends>    
    <data>
        <name>Eros Harem</name>
        <id>2345123465</id>        
    <data>
        <name>Vincent Dagpin</name>
        <id>56783567245</id>        
    </data>
    <data>
        <name>Vrynxzent Kamote</name>
        <id>3456824567</id>        
    </data>
    <paging>
    <next>nextURLHere</next>
    </paging>
</friends>
+5
source share
1 answer

What you need is the root element in your json, I think. what XML is needed.

which I think you can do with

XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "friends");
+8
source

All Articles