如何将 XML/JSON 文件转换为 C# 类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19612215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:24:56  来源:igfitidea点击:

How to convert XML/JSON file to C# class?

c#.netxmljson

提问by

I have XMLfile like this:

我有这样的XML文件:

<?xml version="1.0"?>
<catalog>
    <book id="1" date="2012-02-01">
        <title>XML Developer's Guide</title>
        <price>44.95</price>
        <description>
            An in-depth look at creating applications
            with XML.
        </description>
    </book>
    <book id="2" date="2013-10-16">
        <author>Mark Colsberg</author>
        <title>Dolor sit amet</title>
        <price>5.95</price>
        <description>Lorem ipsum</description>
    </book>
</catalog>

How to quick convert it to C# classes to use access data by LINQ? Do I have to write the class manually for any XML file case? What about JSONformat?

如何快速将其转换为 C# 类以通过 LINQ 使用访问数据?我是否必须为任何 XML 文件案例手动编写类?什么JSON格式?

Is the XSD the only solution?

XSD 是唯一的解决方案吗?

采纳答案by Damian Drygiel

You have two possibilities.

你有两种可能性。

Method 1. XSDtool

方法一、XSD工具



假设您的 XML 文件位于此位置 C:\path\to\xml\file.xmlC:\path\to\xml\file.xml

  1. Open Developer Command Prompt
    You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio ToolsOr if you have Windows 8 can just start typing Developer Command Promptin Start screen
  2. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
  3. Create XSD filefrom your xml file by typing xsd file.xml
  4. Create C# classesby typing xsd /c file.xsd
  1. 打开开发人员命令提示符
    您可以在Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools或者如果您有 Windows 8 可以在开始屏幕中开始键入开发人员命令提示符
  2. 通过键入将位置更改为您的 XML 文件目录 cd /D "C:\path\to\xml"
  3. 通过键入从您的 xml 文件创建XSD 文件xsd file.xml
  4. 通过键入创建C# 类xsd /c file.xsd

And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

就是这样!您已经从 xml 文件中生成了 C# 类C:\path\to\xml\file.cs

Method 2 - Paste special

方法 2 - 特殊粘贴



所需的 Visual Studio 2012+

  1. Copy content of your XML file to clipboard
  2. Add to your solution new, empty class file (Shift+Alt+C)
  3. Open that file and in menu click Edit > Paste special > Paste XML As Classes
    enter image description here
  1. 将 XML 文件的内容复制到剪贴板
  2. 添加到您的解决方案新的,空的类文件(Shift+ Alt+ C
  3. 打开该文件并在菜单中单击 Edit > Paste special > Paste XML As Classes
    在此处输入图片说明

And that's it!

就是这样!

Usage

用法



Usage is very simple with this helper class:

这个助手类的用法非常简单:

using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;

namespace Helpers
{
    internal static class ParseHelpers
    {
        private static JavaScriptSerializer json;
        private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }

        public static Stream ToStream(this string @this)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(@this);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }


        public static T ParseXML<T>(this string @this) where T : class
        {
            var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
        }

        public static T ParseJSON<T>(this string @this) where T : class
        {
            return JSON.Deserialize<T>(@this.Trim());
        }
    }
}

All you have to do now, is:

你现在要做的就是:

    public class JSONRoot
    {
        public catalog catalog { get; set; }
    }
    // ...

    string xml = File.ReadAllText(@"C:\path\to\xml\file.xml");
    var catalog1 = xml.ParseXML<catalog>();

    string json = File.ReadAllText(@"C:\path\to\json\file.json");
    var catalog2 = json.ParseJSON<JSONRoot>();

Here you have some Online XML <--> JSONConverters: Click

这里有一些在线XML <--> JSON转换器:点击

回答by Damian Drygiel

Use the XML Schema Definition Toolxsd.exefound in your framework tools to convert your schema into a serializable class or dataset.

使用框架工具中的XML 架构定义工具xsd.exe将架构转换为可序列化的类或数据集。

xsd file.xsd {/classes | /dataset} [/element:element]
         [/language:language] [/namespace:namespace]
         [/outputdir:directory] [URI:uri]

And in example, whereas the C# class will be generated in the same directory as the xsd tool:

在示例中,C# 类将在与 xsd 工具相同的目录中生成:

xsd /c YourFile.xsd

回答by anis programmer

You can follow this simple step

你可以按照这个简单的步骤

1.Please Add using System.Xml as a reference;
2.Make a class named book in this way



     public class book
            {
                public Nullable<System.DateTime> date{ get; set; }
                public decimal price { get; set; }
                public string title { get; set; }
                public string description { get; set; }
        }

    try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load("Write down full path");
                    XmlNodeList dataNodes = xmlDoc.SelectNodes("/catalog");

                    foreach (XmlNode node in dataNodes)
                    {
                        book objbook = new book();
                     objbook.date=Convert.ToDateTime(node.Attributes["date"].Value);
                       objbook.title=node.SelectSingleNode("title").InnerText;
                   objbook.description=node.SelectSingleNode("description").InnerText;
objbook.price=Convert.ToDecimal(node.SelectSingleNode("price").InnerText);

                    }

                }
catch(Exception ex)
{
throw ex;
}

回答by Ram

Use the super simple way using 'Paste XML As Classes' functionality in Visual studio menu.

使用Visual Studio 菜单中的“将XML 粘贴为类”功能的超级简单方法

1.copy the xml source in the clipboard, something like CTRL+A and CTRL+C

1.复制剪贴板中的xml源代码,类似于CTRL+A和CTRL+C

2.Go to 'Edit' Menu -> Paste Special -> Paste XML As Classes, to paste the generated classes based on the source xml"

2.转到'编辑'菜单->选择性粘贴->将XML粘贴为类,根据源xml粘贴生成的类”

Ref: More steps in detail at this link

参考:在此链接中详细了解更多步骤