Convert Json to XML

3

I have this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml;
using Newtonsoft.Json;
using System.Net;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;

namespace PowderToyUpdater
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WebClient web = new WebClient();
            var value = web.DownloadString("http://powdertoy.co.uk/Browse/Comments.json?ID=1681176&Start=0&Count=20");


            XmlDocument xdoc = (XmlDocument)JsonConvert.DeserializeXmlNode(value);

            XmlWriter w = XmlWriter.Create("comments_.xml");
            xdoc.WriteTo(w);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PowderToyUpdater
{
    public struct Comment
    {
        public string Username;
        public string Userid;
        //public string Gravatar;
        public string CommentContent;
        public string Timestamp;
        public string FormattedUsername;
    }
}

But when JSON is converted to XML and stored in a file, some of the XML is missing.

<?xml version="1.0" encoding="utf-8"?><User><root><Username>Sandwichlizard</Username><UserID>105412</UserID><Gravatar>/Avatars/105412_40.png</Gravatar><Text>front page.</Text><Timestamp>1424281388</Timestamp><FormattedUsername>Sandwichlizard</FormattedUsername></root><root><Username>ndutoit</Username><UserID>133746</UserID><Gravatar>http://www.gravatar.com/avatar/88ff6ca3f7391896d88ea1f6ac46c3f8?s=40&amp;amp;d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&amp;amp;r=pg</Gravatar><Text>what is fp?</Text><Timestamp>1424279967</Timestamp><FormattedUsername>ndutoit</FormattedUsername></root><root><Username>Lord_Bowserinator</Username><UserID>130740</UserID><Gravatar>/Avatars/130740_40.png</Gravatar><Text>fp again</Text><Timestamp>1417569227</Timestamp><FormattedUsername>Lord_Bowserinator</FormattedUsername></root><root><Username>Sandwichlizard</Username><UserID>105412</UserID><Gravatar>/Avatars/105412_40.png</Gravatar><Text>sure.  I will make a tutorial save.  that will be easier than just talking about it here.  I will leave a link in this save when it is ready.  I will also publish it.</Text><Timestamp>1417561239</Timestamp><FormattedUsername>Sandwichlizard</FormattedUsername></root><root><Username>Anonymous100</Username><UserID>92366</UserID><Gravatar>/Avatars/92366_40.png</Gravatar><Text>Sandwich would you mind explaining to me the basic of all thesse fancy filt drives? I know that it has something to do with the fact that a color of filt when beamed at dtec with aray changes the filts color that is next to the dtec, but I dont understand how that info is decoded, and how it is written in the first place.</Text><Timestamp>1417541787</Timestamp><FormattedUsername>Anonymous100</FormattedUsername></root><root><Username>tombattraw</Username><UserID>85950</UserID><Gravatar>http://www.gravatar.com/avatar/a9a4ec31425b097ae496b8f027cdf016?s=40&amp;amp;d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&amp;amp;r=pg</Gravatar><Text>try recording a pong game</Text><Timestamp>1417535992</Timestamp><FormattedUsername>tombattraw</FormattedUsername></root><root><Username>Sandwichlizard</Username><UserID>105412</UserID><Gravatar>/Avatars/105412_40.png</Gravatar><Text>@mecha-man.  sure. I have already started.  I am working on a new printer save using this drive and I realized I needed some things and it forced me into a redesign.  I will PM you.</Text><Timestamp>1417488946</Timestamp><FormattedUsername>Sandwichlizard</FormattedUsername></root><root><Username>mecha-man</Username><UserID>48475</UserID><Gravatar>/Avatars/48475_40.png</Gravatar><Text>@Sandwichlizard: Wanna work together to make it more compact?</Text><Timestamp>1417482098</Timestamp><FormattedUsername>mecha-man</FormattedUsername></root><root><Username>159819</Username><UserID>78051</UserID><Gravatar>/Avatars/78051_40.png</Gravatar><Text>is it posable to ither make a biger screen or smaler pixels?</Text><Timestamp>1417478468</Timestamp><FormattedUsername>159819</FormattedUsername></root><root><Username>0356459</Username><UserID>121388</UserID><Gravatar>http://www.gravatar.com/avatar/56261703f558a3503a1ab238fd4f4dac?s=40&amp;amp;d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&amp;amp;r=pg</Gravatar><Text>sorry man......but hey front page for a long time! :)</Text><Timestamp>1417412356</Timestamp><FormattedUsername>0356459</FormattedUsername></root><root><Username>Sandwichlizard</Username><UserID>105412</UserID><Gravatar>/Avatars/105412_40.png</Gravatar><Text>If someone would like to make a new video for this setup I would happily update the save with credit to the author of said video</Text><Timestamp>1417399984</Timestamp><FormattedUsername>Sandwichlizard</FormattedUsername></root><root><Username>Sandwichlizard</Username><UserID>105412</UserID><Gravatar>/Avatars/105412_40.png</Gravatar><Text>the crappy video is just to demo the drive.  video made way better video's than mine for sure.  thank you for your input.</Text><Timestamp>1417399892</Timestamp><FormattedUsername>Sandwichlizard</FormattedUsername></root><root><Username>0356459</Username><UserID>121388</UserID><Gravatar>http://www.gravatar.com/avatar/56261703f558a3503a1ab238fd4f4dac?s=40&amp;amp;d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&amp;amp;r=pg</Gravatar><Text>video did it better 2 times before. -1</Text><Timestamp>1417318433</Timestamp><FormattedUsername>0356459</FormattedUsername></root><root><Username>zsdrfty</Username><UserID>100327</UserID><Gravatar>/Avatars/100327_40.png</Gravatar><Text>Minecraft is more insane because it has analog computers. oog</Text><Timestamp>1417281395</Timestamp><FormattedUsername>zsdrfty</FormattedUsername></root><root><Username>Imperator</Username><UserID>123921</UserID><Gravatar>/Avatars/123921_40.png</Gravatar><Text>It's so cool that people can actually make a functioning computer within a game.</Text><Timestamp>1417269917</Timestamp><FormattedUsername>Imperator</FormattedUsername></root><root><Username>handicraftsman</Username><UserID>108835</UserID><Gravatar>/Avatars/108835_40.png</Gravatar><Text>Sandwichlizard, you can use my tablets without credits ) It's for you ) id:1677416</Text><Timestamp>1417268811</Timestamp><FormattedUsername>handicraftsman</FormattedUsername></root><root><Username>Ilog123</Username><UserID>104909</UserID><Gravatar>/Avatars/104909_40.png</Gravatar><Text>Try Making a Movie maker so you can copy/paste your film and check em out</Text><Timestamp>1417251254</Timestamp><FormattedUsername>Ilog123</FormattedUsername></root><root><Username>electronic_steve</Username><UserID>96362</UserID><Gravatar>/Avatars/96362_40.png</Gravatar><Text>id:1683229 108,3... i won!</Text><Timestamp>1417237206</Timestamp><FormattedUsername>electronic_steve</FormattedUsername></root><root><Username>zsdrfty</Username><UserID>100327</UserID><Gravatar>/Avatars/100327_40.png</Gravatar><Text>16.7k? We're over 1/10 of the capacity of a single-sided, single-density 5.25" floppy disk!</Text><Timestamp>1417229000</Timestamp><FormattedUsername>zsdrfty</FormattedUsername></root><root><Username>Fulchrum</Username><UserID>95857</UserID><Gravata  <= Aqui falta o restante do xml.

And after converting JSON to XML, how do I use XmlTextReader or XmlReader?

    
asked by anonymous 23.11.2015 / 00:13

2 answers

1

It is recommended that you use the XmlDocument.Save to write this XML document to a file. Using it is quite simple, here's how I've altered the excerpt from the Main method of your code to use it:

WebClient web = new WebClient();
var value = $"{{ user: {web.DownloadString("http://powdertoy.co.uk/Browse/Comments.json?ID=1681176&Start=0&Count=20")} }}";

XmlDocument xdoc = JsonConvert.DeserializeXmlNode(value, "root");

xdoc.Save("comments_.xml");

Note also that I made a change in the JSON obtained from the web service so that it became valid for conversion by the JsonConvert.DeserializeXmlNode method. According to the Json.NET documentation for you to convert a JSON document to XML, it is necessary for this JSON document to have a single object in its root. The JSON returned by the web service did not follow this pattern and came in array format. This documentation page talks about this.

About the second part of your question where you ask about using System.Xml.XmlReader or System.Xml.XmlReader .

As described in the System.Xml.XmlReader documentation, its usage is no longer recommended and the SYSTEM.Xml.XmlReader 'should be used instead.

Since it would not be worth it to demonstrate everything you can do with System.Xml.XmlReader , and your question also did not spell out exactly what you'd like to do with it, I'll recommend you read the documentation for that class on MSDN, since you can find several well-explained usage examples. System.Xml.XmlReader documentation.

    
28.11.2015 / 00:33
-1

This code below will generate an uncut XML, I did a fiddler for you with the code:

WebClient web = new WebClient();
var value = web.DownloadString("http://powdertoy.co.uk/Browse/Comments.json?ID=1681176&Start=0&Count=20");

            string json = @"{
   '?xml': {
     '@version': '1.0',
     '@standalone': 'no'
   },
   'root': {
     'minhaclasse':
[
" + value.Replace("'","\'") + @"

]
  }
}";

XmlDocument xml = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

xml.Save(@"c:\caminho\teste.xml");

I made a basic example with XmlReader for you, the code below also runs here at fiddler .

public class Program
{
	public static void Main()
	{
		
		String xmlString =
			@"<bookstore>
				<book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
					<title>The Autobiography of Benjamin Franklin</title>
					<author>
						<first-name>Benjamin</first-name>
						<last-name>Franklin</last-name>
					</author>
					<price>8.99</price>
				</book>
			</bookstore>";
		
		// Create an XmlReader
		using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
		{
			reader.ReadToFollowing("book");
			reader.MoveToFirstAttribute();
			string genre = reader.Value;
			Console.WriteLine("The genre value: " + genre);
		
			reader.ReadToFollowing("title");
			Console.WriteLine("Content of the title element: " + reader.ReadElementContentAsString());
		}
	}
}

There is still the option to play Json direct to object, I say this by the title of your question, which you changed, in case you are interested, you can get the direct link through webClient and transform it into an object created by you. In that case you would not have to do anything with XML.

UPDATE

As requested in the comment I made a code putting it all together. This code does not write to a file, it takes Json, converts to XML, plays to a String, and reads. Here (Fiddle) you can see the code running.

            WebClient web = new WebClient();
            var value = web.DownloadString("http://powdertoy.co.uk/Browse/Comments.json?ID=1681176&Start=0&Count=20");

            string json = @"{
   '?xml': {
     '@version': '1.0',
     '@standalone': 'no'
   },
   'root': {
     'minhaclasse':
[
" + value.Replace("'", "\'") + @"

]
  }
}";

            XmlDocument xml = (XmlDocument)JsonConvert.DeserializeXmlNode(json);


            var xmlString = xml.InnerXml;


            using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
            {
                reader.MoveToContent();
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {

                        
                        if (reader.Name == "Username")
                        {
                            XElement el = XNode.ReadFrom(reader) as XElement;
                            if (el != null)
                            {
                                Console.Write("Username : ");
                                Console.WriteLine(el.Value);
                            }
                        }
                    }
                }
            }	
}
    
23.11.2015 / 01:24