Json.NET: Seamless JSON-XML Conversion
Json.NET simplifies the conversion between JSON and XML formats using its powerful JsonConvert
class. This class offers straightforward methods for handling this common data transformation task.
XML to JSON Conversion
To transform an XML string (represented as xml
) into its JSON equivalent:
Instantiate an XmlDocument
object (doc
) and load the XML string:
<code class="language-csharp">XmlDocument doc = new XmlDocument(); doc.LoadXml(xml);</code>
Employ the JsonConvert.SerializeXmlNode
method to serialize the XmlDocument
into a JSON string:
<code class="language-csharp">string jsonText = JsonConvert.SerializeXmlNode(doc);</code>
JSON to XML Conversion
Conversely, converting a JSON string (json
) to XML involves these steps:
Deserialize the JSON string into an XmlDocument
using JsonConvert.DeserializeXmlNode
:
<code class="language-csharp">XmlDocument doc = JsonConvert.DeserializeXmlNode(json);</code>
Further Reading
For comprehensive details and advanced usage scenarios, consult the official Json.NET documentation on JSON-XML conversion: https://www.php.cn/link/a8578be2fe9a67d039ee7b4f18697286
The above is the detailed content of How Can I Convert JSON to XML and XML to JSON Using Json.NET?. For more information, please follow other related articles on the PHP Chinese website!