Hey I'm new in Programming ,can anyone please help me to convert a XML file to JSON using C #

xml
json

#1

using System;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Linq;
namespace ConsoleApp1
{
class Program

{
    static void Main()
    {
        var xml =
        @"<Student>
                <student Name>Shruthi</student Name>
                <SSN>45678</SSN>
                <Course>Electronics and communication</Course>
                <Address>
                    <Line 1="">#1, 6th cross</Line 1>
                    <Line 2="">Victoria Layout</Line 2>
                    <City>Bangalore</City
                    <Country>India</Country>
                </Address>
          </Student>
          <Student>
                <student Name>Preethi</student Name>
                <SSN>45679</SSN>
                <Course>Electronics and communication</Course>
                <Address>
                    <Line 1="">#1, 6th cross</Line 1>
                    <Line 2="">Victoria Layout</Line 2>
                    <City>Bangalore</City>
                    <Country>India</Country>
                    </Address>
          </Student>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Student")
            .ToDictionary(
                c => c.Attribute("Name").Value,
                c => c.Value
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }
    private static Type GetType(string type)
    {
        switch (type)
        {
            case "Integer":
                return typeof(int);
            case "String":
                return typeof(string);
            case "Boolean":
                return typeof(bool);
            default:
                return typeof(int);
        }
    }
}

}


#2

Hi @dhanushreeks,
There was a question like this on Stack Overflow, here is how it was answered:

Original Question: "How to convert JSON to XML or XML to JSON?

I started to use Json.NET to convert a string in JSON format to object or vice versa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to XML format and vice versa?"

Original Answer: Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

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

Here is the link to the Documentation: https://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm

Hope This Helps!
~ Izzy


#3

Thank you @isabelsandoval


#4

Glad to help! :smile:


#5

hey! if there are different datatypes with in the input (signed numbers ,etc)which give as an sql input,how to define in c#?