简体   繁体   English

在ASP.NET Core MVC中将XML转换为JSON

[英]XML to JSON in ASP.NET Core MVC

I get XmlReader whith data. 我得到XmlReader蒙山数据。 How to convert it to JSON in ASP.NET Core MVC? 如何在ASP.NET Core MVC中将其转换为JSON?

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

I eventually found a solution that worked for me, hope its what you're looking for. 我最终找到了一个对我有用的解决方案,希望它能为您提供所需的解决方案。 The output would be: 输出为:

{"something":"someValue"} {“某事”:“ 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM