首页 > 解决方案 > 如何展平通过转换 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 转换模板。

非常感谢,凯

标签: c#jsonxml

解决方案


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

推荐阅读