Sam Boniface
Sam Boniface

Reputation: 11

Converting Multiple json files to xml files

I'm a relatively new programmer and therefore have limited knowledge; however, I've been asked to create a program to convert loads of json files to xml files. There are a lot of them, and they're all different in terms of content (and i don't know exactly what's in them).

I've tried the following code

static void ProcessFiles(string path)
    {
        string[] files;
        string[] directories;

        XmlDocument xml = new XmlDocument();
        files = Directory.GetFiles(path);
        foreach (string file in files)
        {
            using (StreamReader r = new StreamReader(file))
            {
                string j = r.ReadToEnd();
                string json = JsonConvert.DeserializeObject(j).ToString();
                xml = JsonConvert.DeserializeXmlNode(json);

                Console.Write(xml);
            }
        }

        directories = Directory.GetDirectories(path);
        foreach(string directory in directories)
        {                
            ProcessFiles(directory);
        }
    }

I've managed to get this as my string 'json' and then get an error.

    [
  {
    "Start": "date",
    "Finish": "date",
    "Subject": "",
    "Comments": "",
    "Site": "address",
    "Location": null,
    "Status": false,
    "Arrived": true,
    "Noshow": false,
    "Services": "Initial Consultation",
    "Attendees": [
      {
        "AccountId": 1111,
        "AccountType": "MP",
        "Name": "MMS (FP), Support "
      },
      {
        "AccountId": 2220915,
        "AccountType": "PA",
        "Name": "Test, Patient "
      }
    ]
  },
]

I've been looking online for a solution but no luck so far. Can anyone help please?

Upvotes: 0

Views: 986

Answers (2)

Enigmativity
Enigmativity

Reputation: 117037

It seems to me that you just need this:

static void ProcessFiles(string path)
{
    foreach (string file in Directory.GetFiles(path))
    {
        JsonConvert.DeserializeXmlNode(File.ReadAllText(file)).Save(file + ".xml");
    }

    foreach (string directory in Directory.GetDirectories(path))
    {
        ProcessFiles(directory);
    }
}

Upvotes: 0

er-sho
er-sho

Reputation: 9771

You are close to your goal,

So now you are doing like,

  1. Read string json from StreamReader with ReadToEnd
  2. And then deserialized into dynamic variable.
  3. Then load into xml.

But at point 3 you are trying to pass json string to LoadXml method where as LoadXml want xml string as input.

So far, newtonsoft have one method that can directly convert your json to xml

XmlDocument xdoc = JsonConvert.DeserializeXmlNode(json);

So now your code look like,

//Your code as it is

using (StreamReader r = new StreamReader(file))
{
    string json = r.ReadToEnd();
    xdoc = JsonConvert.DeserializeXmlNode(json);

    xdoc.Save(file + ".xml");
}

//Your code as it is

Upvotes: 1

Related Questions