This article is intended to show you how to convert the acquired XML document into a corresponding JSON format string by using C # and then output it to the front of the page for JavaScript code parsing. Perhaps you can directly use JavaScript code to read XML through Ajax, and then directly parse the contents of it, perhaps more directly. However, the code given in this article is intended to illustrate how this transformation is done through native C # code. In addition, you can still borrow some third-party class libraries or more advanced ones. NET Library objects to implement transformations. Let's take a look at some of the simpler methods described here, but only if you have a supported class library and objects to use.
- Using the Json.NET class library
The prerequisite is to first download and install the Json.NET class library, where you can find http://json.codeplex.com/
Here is an example:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Xml;usingNewtonsoft.json;namespacejsonconverter{classProgram {Static voidMain (string[] args) { stringXML ="<test><name>test class</name><x>100</x><y>200</y></test> "; XmlDocument Doc=NewXmlDocument (); Doc. LOADXML (XML); stringJSON =Newtonsoft.Json.JsonConvert.SerializeXmlNode (DOC); Console.WriteLine ("JSON, XML: {0}", JSON); Console.ReadLine (); } }}
JSON is a lightweight data interchange format that can be easily encoded in the form of an object by a page's JavaScript, making it easy to manipulate data.
Ajax-based pages use the XMLHttpRequest object to receive data from the server in response to a user's request, and when the returned data is in XML format, it can be converted to a JSON-formatted string, making it easier to process the data through JavaScript.
Many applications store data in XML format and send the data in JSON format to the client for further processing. To do this, they must convert the XML format to JSON format.
Convert XML to JSON in C #