XML到JSON在ASP.NET核心MVC

问题描述:

我得到XmlReader与数据。如何将它转换为ASP.NET Core MVC中的JSON?XML到JSON在ASP.NET核心MVC

例如:

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); 
} 

我最终发现,为我工作的解决方案,希望它的你在找什么。输出将是:

{ “东西”: “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; 
}