14

I've been using Json.Net to parse JSON to object and convert to XMLDocument but I got

InvalidOperationException This document already has a 'DocumentElement' node.

I have this 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);
        }
    }
}

did i miss some settings?

I expect to have something like this as 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>
3
  • Hint: What would you expect the resulting XML to look like? Also, I'm curious about why you'd want to do this. JSON is just as expressive as XML (if not more so), so why bother converting it? Commented Aug 2, 2012 at 3:28
  • because some instance, i do not know what are my json contains. i can't parse it to any object type since i do not know what properties they have. make sense? Commented Aug 2, 2012 at 3:33
  • his point is, even if you can't map it to an object, why not leave it as json? Commented Aug 2, 2012 at 3:35

1 Answer 1

21

What you need is a root element in your json I think. which is what XML needs.

which I think you can do by

XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "friends");
Sign up to request clarification or add additional context in comments.

2 Comments

you mean XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); will be initialized to have root element?
oh.. i think, i just missed this string parameter for root element.. thanks.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.