如何使用 C#/LINQ 将 XML 转换为 JSON?

How to convert XML to JSON using C#/LINQ?(如何使用 C#/LINQ 将 XML 转换为 JSON?)
本文介绍了如何使用 C#/LINQ 将 XML 转换为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有以下需要在服务器中转换为 JSON 的 XML 文件.最初我以为我会将它转换为字典,然后使用 JavaScriptSerializer 将其转换为 JSON,但由于每列可能有不同的值类型,我认为它不会起作用.以前有人在 C#/LINQ 中做过类似的事情吗?

I have the following XML file that I need to convert to JSON in the server. Initially I thought I would convert it to a Dictionary and then use the JavaScriptSerializer to turn it into JSON but since each column could have a different value type, I don't think it would work. Has anyone done something similar before in C#/LINQ?

我需要保留每列的值类型(布尔、字符串、整数).

I need to preserve the Value Types(Boolean, String, Integer) of each column.

如果我刚刚开始使用 XML,我将不胜感激.谢谢.

I would appreciate any advice on this as Im just starting to work with XML. Thanks.

<Columns>
 <Column Name="key1" DataType="Boolean">True</Column>
 <Column Name="key2" DataType="String">Hello World</Column>
 <Column Name="key3" DataType="Integer">999</Column>
</Columns>

推荐答案

using System;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        var xml = 
        @"<Columns>
          <Column Name=""key1"" DataType=""Boolean"">True</Column>
          <Column Name=""key2"" DataType=""String"">Hello World</Column>
          <Column Name=""key3"" DataType=""Integer"">999</Column>
        </Columns>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Column")
            .ToDictionary(
                c => c.Attribute("Name").Value, 
                c => c.Value
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }
}

产生:

{"key1":"True","key2":"Hello World","key3":"999"}

显然,这会将所有值都视为字符串.如果您想保留底层类型语义,您可以执行以下操作:

Obviously this treats all the values as strings. If you want to keep the underlying type semantics you could do the following:

using System;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        var xml = 
        @"<Columns>
          <Column Name=""key1"" DataType=""System.Boolean"">True</Column>
          <Column Name=""key2"" DataType=""System.String"">Hello World</Column>
          <Column Name=""key3"" DataType=""System.Int32"">999</Column>
        </Columns>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Column")
            .ToDictionary(
                c => c.Attribute("Name").Value, 
                c => Convert.ChangeType(
                    c.Value,
                    typeof(string).Assembly.GetType(c.Attribute("DataType").Value, true)
                )
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }
}

产生:

{"key1":true,"key2":"Hello World","key3":999}

如果您无法修改底层 XML 结构,您将需要一个自定义函数,该函数将在您的自定义类型和底层 .NET 类型之间进行转换:

And if you cannot modify the underlying XML structure you will need a custom function that will convert between your custom types and the underlying .NET type:

using System;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        var xml = 
        @"<Columns>
          <Column Name=""key1"" DataType=""Boolean"">True</Column>
          <Column Name=""key2"" DataType=""String"">Hello World</Column>
          <Column Name=""key3"" DataType=""Integer"">999</Column>
        </Columns>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Column")
            .ToDictionary(
                c => c.Attribute("Name").Value, 
                c => Convert.ChangeType(
                    c.Value, 
                    GetType(c.Attribute("DataType").Value)
                )
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }

    private static Type GetType(string type)
    {
        switch (type)
        {
            case "Integer":
                return typeof(int);
            case "String":
                return typeof(string);
            case "Boolean":
                return typeof(bool);
            // TODO: add any other types that you want to support
            default:
                throw new NotSupportedException(
                    string.Format("The type {0} is not supported", type)
                );
        }
    }
}

这篇关于如何使用 C#/LINQ 将 XML 转换为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)