【问题标题】:How to convert XML/JSON file to C# class?如何将 XML/JSON 文件转换为 C# 类?
【发布时间】:2013-11-05 21:25:04
【问题描述】:

我有这样的 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>

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

XSD 是唯一的解决方案吗?

【问题讨论】:

  • 搜索c# xml json 序列化.
  • 你真的在说classes吗?或者你的意思是instances 的一个合适的class
  • @MarcinJuraszek,yan.kun,我想你误解了这个问题......

标签: c# .net xml json


【解决方案1】:

你有两种可能。

方法一、XSD工具


假设您的 XML 文件位于此位置 C:\path\to\xml\file.xml
  1. 打开开发者命令提示符
    你可以在Start Menu &gt; Programs &gt; Microsoft Visual Studio 2012 &gt; Visual Studio Tools找到它 或者,如果您使用的是 Windows 8,则可以在 开始屏幕 中开始输入 Developer Command Prompt
  2. 通过键入cd /D "C:\path\to\xml" 将位置更改为您的 XML 文件目录
  3. 通过键入xsd file.xml 从您的 xml 文件创建 XSD 文件
  4. 通过键入 xsd /c file.xsd 创建 C# 类

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

方法 2 - 选择性粘贴


需要 Visual Studio 2012+
  1. 将 XML 文件的内容复制到剪贴板
  2. 向您的解决方案添加新的空类文件 (Shift+Alt+C)
  3. 打开该文件并在菜单中单击Edit &gt; Paste special &gt; Paste XML As Classes

就是这样!

用法


这个帮助类的使用非常简单:

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());
        }
    }
}

你现在要做的就是:

    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>();

这里有一些在线XML &lt;--&gt; JSON 转换器:Click

【讨论】:

  • +1 表示“将 XML 粘贴为类”,我不知道这个选项。绝对可以派上用场……
  • 在类文件的代码中选择“编辑”>“选择性粘贴”菜单时,确保类文件所在的 Visual Studio 项目的“目标框架”设置为:.NET Framework 3.5+ for 'Paste JSON as Classes' .NET Framework 4.5+ for 'Paste XML as Classes' 否则这些选项不会出现。 “目标框架”设置位于项目属性 > 应用程序下。
  • 不错的功能。谢谢!
  • 这个粘贴“XML as classes”选项非常棒,
【解决方案2】:

您可以按照这个简单的步骤进行操作

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;
}

【讨论】:

    【解决方案3】:

    使用您的框架工具中的XML Schema Definition Toolxsd.exe 将您的架构转换为可序列化的类或数据集。

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

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

    xsd /c YourFile.xsd
    

    【讨论】:

      【解决方案4】:

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

      1.复制剪贴板中的xml源,比如CTRL+A和CTRL+C

      2.转到“编辑”菜单 -> 选择性粘贴 -> 将 XML 粘贴为类,以粘贴基于源 xml 生成的类”

      Ref: More steps in detail at this link

      【讨论】:

        【解决方案5】:

        这是另一种使用开源库 Cinchoo ETL 解析 xml 文件的简单方法

        如下定义 POCO 类

        public class Book
        {
            [ChoXPath("@id")]
            public int Id { get; set; }
            [ChoXPath("@date")]
            public DateTime Date { get; set; }
            [ChoXPath("author")]
            public string Author { get; set; }
            [ChoXPath("title")]
            public string Title { get; set; }
            [ChoXPath("price")]
            public double Price { get; set; }
            [ChoXPath("description")]
            public string Description { get; set; }
        }
        

        将它用于下面的解析器

        using (var r = new ChoXmlReader<Book>("*** Xml file path ***")
               .WithXPath("//catalog/book", true)
               )
        {
            foreach (var rec in r)
                rec.Print();
        }
        

        小提琴样例:https://dotnetfiddle.net/3UI82F

        【讨论】:

          猜你喜欢
          • 2014-11-11
          • 2014-10-26
          • 1970-01-01
          • 2017-12-14
          • 1970-01-01
          • 2012-06-17
          • 1970-01-01
          • 1970-01-01
          • 2017-06-18
          相关资源
          最近更新 更多