Search code examples
jsonxmlasp.net-coreasp.net-core-mvcxmlreader

XML to JSON in ASP.NET Core MVC


I get XmlReader whith data. How to convert it to JSON in ASP.NET Core MVC?

For example:

using (SqlCommand command = new SqlCommand("SELECT * FROM Sample for XML AUTO", connection as SqlConnection)){
    XmlReader xml = command.ExecuteXmlReader();
    xml.Read();
    //convert xml.ReadOuterXml() to json
    return new ObjectResult(json);
}

Solution

  • I eventually found a solution that worked for me, hope its what you're looking for. The output would be:

    {"something":"someValue"}

    // References:
    //using System.Xml;
    //using Newtonsoft.Json;
    //using System.Xml.Linq;
    
    var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><example><something>someValue</something></example>";
    using (var xReader = XmlReader.Create(new StringReader(input))) {                    
        // This line skips the XML declaration, eg "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - you can skip this if you don't have declaration as in your case
        xReader.MoveToContent();
        // Gets the actual XMLElement, if any
        xReader.Read();
        // Convert the xReader to an XNode for the Json serializer
        XNode node = XNode.ReadFrom(xReader);
        // Json output
        string jsonText = JsonConvert.SerializeXNode(node);
        return jsonText;
    }