【问题标题】:How to flatten XML created from converting JSON如何展平通过转换 JSON 创建的 XML
【发布时间】:2019-06-26 09:55:39
【问题描述】:

使用以下方法将 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# json xml


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多