C#中XML转JSON时,如何将含JSON格式值的节点解析为JSON对象?
问题
我有如下XML:
"<root><name>john</name><info>{\"age\":25,\"city\":\"NYC\"}</info></root>"
使用JsonConvert.SerializeXmlNode(doc)方法转换时,得到的输出如下:
{ "root":{ "name":"john", "info":"{\"age\":25,\"city\":\"NYC\"}" } }
但我期望得到如下格式的输出:
{ "root":{ "name":"john", "info":{ "age":25, "city":"NYC" } } }
解决方案
问题核心是XML的<info>节点内容是JSON格式的字符串,SerializeXmlNode只会将其视为普通文本,不会自动解析为JSON对象。要实现预期结果,需要先手动解析该JSON字符串,再替换XML节点内容后序列化。
实现步骤(使用XmlDocument)
- 加载XML文档
- 提取
<info>节点内的JSON字符串并解析为JObject - 清空原
<info>节点,将解析后的JSON对象转换为XML节点并插入 - 序列化处理后的XML文档为JSON
示例代码:
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Xml; // 原始XML字符串 string xmlStr = "<root><name>john</name><info>{\"age\":25,\"city\":\"NYC\"}</info></root>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlStr); // 获取info节点 XmlNode infoNode = doc.SelectSingleNode("//info"); if (infoNode != null && !string.IsNullOrEmpty(infoNode.InnerText)) { // 解析JSON字符串为JObject JObject jsonObj = JObject.Parse(infoNode.InnerText); // 清空原节点内容 infoNode.RemoveAll(); // 将JObject转为XML节点并导入到当前文档 XmlNode jsonXmlNode = JsonConvert.DeserializeXmlNode(jsonObj.ToString(), "temp"); infoNode.AppendChild(doc.ImportNode(jsonXmlNode.FirstChild, true)); } // 序列化XML为格式化后的JSON string outputJson = JsonConvert.SerializeXmlNode(doc, Formatting.Indented); Console.WriteLine(outputJson);
替代方案(使用XDocument,LINQ to XML)
如果项目中使用LINQ to XML,可采用以下代码:
using Newtonsoft.Json.Linq; using System.Xml.Linq; XDocument xDoc = XDocument.Parse(xmlStr); XElement infoElement = xDoc.Descendants("info").FirstOrDefault(); if (infoElement != null) { // 解析JSON字符串 JObject jsonObj = JObject.Parse(infoElement.Value); // 将JSON转为XML并替换原info元素内容 infoElement.ReplaceNodes(XElement.Parse(jsonObj.ToString())); } string outputJson = JsonConvert.SerializeXNode(xDoc, Formatting.Indented);
两种方案执行后都会输出你期望的JSON格式:
{ "root": { "name": "john", "info": { "age": 25, "city": "NYC" } } }
内容的提问来源于stack exchange,提问作者ritush love
相关产品推荐
相关产品推荐

