c# - 如何展平通过转换 JSON 创建的 XML
问题描述
使用以下命令将 JSON 转换为 XML 后:
var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(Encoding.ASCII.GetBytes(json), new XmlDictionaryReaderQuotas()));
我得到类似于以下的输出:
<a type="object">
<b type="array">
<item type="object">
...
</item>
<item type="object">
...
</item>
</b>
</a>
有谁知道实际上使 XML 看起来像这样的一个很好的简单方法:
<a type="object">
<b type="object">
...
</b>
<b type="object">
...
</b>
</a>
我需要这种格式来匹配我的 XSLT 转换模板。
非常感谢,凯
解决方案
使用 XML Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication117
{
class Program
{
const string INPUT_FILE = @"c:\temp\test.xml";
const string OUTPUT_FILE = @"c:\temp\test1.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(INPUT_FILE);
XElement b = doc.Descendants("b").FirstOrDefault();
List<XElement> items = b.Descendants("item").Select(x =>
new XElement("b", new object[] {
new XAttribute("type", "object"),
x.Nodes()
})
).ToList();
b.ReplaceWith(items);
doc.Save(OUTPUT_FILE);
}
}
}
推荐阅读
- corda - 无法使 Corda 测试网节点可发布
- node.js - 使用 NG NEW 创建 Angular 项目这些天从来没有用过 - 以错误代码 EPERM 结尾
- php - php join 多个查询结果 laravel
- javascript - 向功能组件添加 react props
- delphi - 以 dB 为单位的声级计算
- javascript - MongoDB:尚未为模型“用户”注册模式
- flutter - Flutter 从服务器的响应返回数组
- python - 我可以信任 ZipInfo.file_size 吗?
- react-native - 单击图像的屏幕截图 react-naitve
- wordpress - 如何以低于所需购物车价值的价格限制 woocommerce 中的客户订单