
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert XML to JSON and JSON Back to XML using Newtonsoft.Json
Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter.
Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the two
SerializeXmlNode
The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text.
DeserializeXmlNode
The second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode.
Example 1
static void Main(string[] args) { string xml = @"Alanhttp://www.google1.com Admin1"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); Console.ReadLine(); }
Output
{"person":{"@id":"1","name":"Alan","url":"http://www.google1.com","role":"Admin1"}}
Example 2
static void Main(string[] args) { string json = @"{ '?xml': { '@version': '1.0', '@standalone': 'no' }, 'root': { 'person': [ { '@id': '1', 'name': 'Alan', 'url': 'http://www.google1.com' }, { '@id': '2', 'name': 'Louis', 'url': 'http://www.yahoo1.com' } ] } }"; XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); Console.WriteLine(json); Console.ReadLine(); }
Output
'?xml': { '@version': '1.0', '@standalone': 'no' }, 'root': { 'person': [ { '@id': '1', 'name': 'Alan', 'url': 'http://www.google1.com' }, { '@id': '2', 'name': 'Louis', 'url': 'http://www.yahoo1.com' } ] }
Advertisements