0

I'm trying to rewrite a php function to C#. The php function converts an XML string to JSON.

At first, I came up with this:

string[] zips = { "27249","27215"}; // Request.Form.Get("zip").ToArray();

        List<string> listings = new List<string>();
        var webClient = new WebClient();

        for (int i = 0; i != zips.Length; i++)
        {

            string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
            var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(returnXml);
            listings.Add(json);
            Response.Write(json);
        }

But the output included encoded characters, which wasn't what I wanted.

Then, using JSON.NET, I replaced the loop body with this:

string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
            var xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(returnXml);

            var json = JsonConvert.SerializeXmlNode(xmlDoc);
            listings.Add(json);

What bothers me about this is thatthe conversion of the Xml string to an XmlDocument just so that I can convert it back to a JSON string seems unnecessary. I want the JSON string for later use in a jQuery function.

How can I make the first version work just using intrinsic .NET methods?

Thanks.

4
  • if you are insisting on transforming Xml to JSON then why are you opposed to creating an Xml object? Commented Jun 25, 2014 at 23:50
  • I'm not opposed to it, I'm mostly curious about why its necessary in the first place. If the incoming string is converted from XML, why bother to do another conversion in order to turn it back to a JSON string? Commented Jun 25, 2014 at 23:56
  • that's because an XmlDoc has validated and "transformed" the string to Xml. Commented Jun 25, 2014 at 23:59
  • you are calling an Xml argument method, why not write your own? Commented Jun 26, 2014 at 0:02

1 Answer 1

1

I can't tell you if there is a pre-made tool which does what you are looking for, but if you are looking to squeeze every bit of performance from this conversion, you can use JsonReader to read the JSON stream, and then use XmlWriter to output it to XML stream

With that said, if JSON you are getting comes from internet, you are unlikely going to significantly improve performance. But you are likely to introduce bugs. I would advice against that

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.