Ankit Saraogi

Ankit Saraogi

  • NA
  • 10
  • 11.2k

How do I populate XML (converted from JSON) to data grid vie

Feb 18 2018 11:47 AM
My main objective is to convert a json file to CSV format with some formatting.
 
For that I have converted the json to xml.
 
Now, I want to populate the nested XML to a datagridview and then further process some formatting commands.
 
The issue is that one parent table and child table of the converted XML file are having the same name 'item'.
 
Please help me resolve the issue. The primary goal is to convert the file as is done by the website https://json-csv.com
 
I do not prefer using any third party reference. Please let me know if it can done using System.Runtime.Serialization.Json
 
The error received by me is
 
The table (item) cannot be the child table to itself in nested relations.
 
My code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Runtime.Serialization;  
  10. using System.Xml; using System.Xml.Linq;  
  11. using System.ServiceModel.Web;  
  12. using System.Runtime.Serialization.Json;  
  13. using System.Xml.XPath;  
  14. namespace JsonToCsv  
  15. {  
  16. public partial class Form1 : Form  
  17. {  
  18. public Form1()  
  19. {  
  20. InitializeComponent();  
  21. }  
  22. private void button1_Click(object sender, EventArgs e)  
  23. {  
  24. string Text = System.IO.File.ReadAllText(@"C:\0.json");  
  25. var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(Text), new System.Xml.XmlDictionaryReaderQuotas());  
  26. var root = XElement.Load(jsonReader);  
  27. DataSet ds = new DataSet();  
  28. System.IO.StringReader Reader = new System.IO.StringReader(root.ToString());  
  29. richTextBox1.Text = root.ToString();  
  30. ds.ReadXml(Reader);  
  31. DataTable dt = new DataTable();  
  32. ds.Tables.Add(dt);  
  33. dataGridView1.DataSource = dt;  
  34. } } }  
The JSON file, the XML generated by the program and the output required are attached

Attachment: Code.rar

Answers (2)