Skip to content

Instantly share code, notes, and snippets.

@jj09
Last active April 20, 2021 12:22
Show Gist options
  • Save jj09/c401d7066a2df1437987d4803fffcdb6 to your computer and use it in GitHub Desktop.
Save jj09/c401d7066a2df1437987d4803fffcdb6 to your computer and use it in GitHub Desktop.
Convert XML to JSON in C#
using Newtonsoft.Json;
using System.IO;
using System.Xml;
namespace ConvertXml2Json
{
class Program
{
static void Main(string[] args)
{
const string DirectoryPath = @"../../../shanselman-blog/";
string[] files = Directory.GetFiles(DirectoryPath);
foreach (string fileName in files)
{
ProcessFile(fileName);
}
}
private static void ProcessFile(string fileName)
{
if (fileName.Contains("feedback"))
{
return;
}
string xml = File.ReadAllText(fileName);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
File.WriteAllText(fileName.Replace(".xml", ".json"), json);
}
}
}
@Vikas-jk
Copy link

Vikas-jk commented Apr 20, 2021

Excellent example, recently I published similar article on Converting JSON to XML and Vice-versa in C#.
Using "Newtonsoft.Json" and without using it also, might be helpful for developers, so here is the link
Converting JSON to XML OR XML to JSON using C#

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment