How to convert JSON to XML or XML to JSON?

后端 未结 13 1282
借酒劲吻你
借酒劲吻你 2020-11-22 05:43

I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to X

13条回答
  •  独厮守ぢ
    2020-11-22 06:09

    I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:

    public XmlDocument JsonToXML(string json)
    {
        XmlDocument doc = new XmlDocument();
    
        using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
        {
            XElement xml = XElement.Load(reader);
            doc.LoadXml(xml.ToString());
        }
    
        return doc;
    }
    

    Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.

提交回复
热议问题