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

15

我有这样的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是唯一的解决方案吗?


你真的在谈论“类”吗?还是你指的是适当“类”的实例? - germi
1
@MarcinJuraszek,yan.kun,我认为你们误解了问题...... - Thomas Levesque
5个回答

60
你有两种可能性。
方法1. XSD工具
假设你的XML文件位于此位置C:\path\to\xml\file.xml
1.打开Developer Command Prompt,您可以在开始菜单中找到它:Microsoft Visual Studio 2012>Visual Studio工具。如果您使用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#类。
就这样!您已经从xml文件生成了C#类,存储在C:\path\to\xml\file.cs中。
方法2-特殊粘贴
需要Visual Studio 2012或更高版本。
1.将您的XML文件内容复制到剪贴板中。
2.向解决方案添加新的空类文件(Shift + Alt + C)。
3.打开该文件并单击菜单中的Edit>Paste special>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 <--> JSON转换器:点击这里


12
对于"粘贴 XML 为类"的选项我给出+1,我之前不知道这个选项,它绝对会很方便... - Thomas Levesque
5
在类文件代码中选择“编辑”>“特殊粘贴”菜单时,请确保您的类文件所在的Visual Studio项目已将其“目标框架”设置为:对于“将JSON粘贴为类”,请使用.NET Framework 3.5+。对于“将XML粘贴为类”,请使用.NET Framework 4.5+。否则,这些选项将不会出现。“目标框架”设置位于“项目属性”>“应用程序”下。 - Rikin Patel
不错的功能。谢谢! - Semen Shekhovtsov
这个“将XML转换为类”的选项真的很棒。 - Yahya Hussein

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

0

这里有另一种使用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


0
使用在框架工具中找到的XML模式定义工具xsd.exe,将您的模式转换为可序列化的类或数据集。
xsd file.xsd {/classes | /dataset} [/element:element]
         [/language:language] [/namespace:namespace]
         [/outputdir:directory] [URI:uri]

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

xsd /c YourFile.xsd

0

使用Visual Studio菜单中的'Paste XML As Classes'功能,以超级简单的方式。

1.将XML源代码复制到剪贴板中,例如CTRL+A和CTRL+C。

2.转到“编辑”菜单 -> “特殊粘贴” -> “将XML作为类粘贴”,以粘贴基于源XML生成的类。

参考:此链接中有更详细的步骤


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接