Convert Json to XML

Asked

Viewed 576 times

3

I have that 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, part of 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?

  • 1

    In the question title is to convert json to object, in the question body you are talking about a cut XML. Compose the question correctly.

  • Why do you need data as XML? It would not be better to store it as JSON since it is being retrieved from the web service in this way?

  • Nathan, why didn’t my answer solve your problem? I tested what I said on it very well before posting here, and yet I’m with -1. That doesn’t seem fair at all.

2 answers

1

It is recommended that you use the method XmlDocument.Save to write this XML document to a file. Using it is very simple, see how I changed the Main method snippet from 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 to the JSON obtained from the web service so that it became valid for conversion by the method JsonConvert.DeserializeXmlNode. According to the Json.NET documentation for you to convert a JSON document to XML, it is necessary that this JSON document has a single object at its root. JSON returned by 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 the System.Xml.XmlReader or System.Xml.XmlReader.

As described in the documentation of System.Xml.XmlReader, its use is no longer recommended and System.xml.Xmlreader` should be used instead.

As it would not be worth it for me to demonstrate all that is possible to do with the System.Xml.XmlReader, and your question also did not explain exactly what you would like to do with it, I will recommend you read the documentation of this class in MSDN, as you can find several examples of use well explained. Documentation of System.Xml.XmlReader.

-1

This code below will generate an XML without cuts, I made 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 on 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, if you are interested you can take the direct link by Webclient and turn into any object created by you. Then you wouldn’t have to do anything with XML.

UPDATING

As requested in the comment I made a code joining everything. This code does not save to file, it takes Json, converts to XML, plays in a String and reads. Aqui (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);
                            }
                        }
                    }
                }
            }	
}

  • Could you put that json here? http://powdertoy.co.uk/Browse/Comments.json?ID=1681176&Start=0&Count=20

  • The example of converting json com to XML is with this link there.

  • I made a code that I think is what you want. If answer do not forget to mark the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.