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

4

5 回答 5

60

你有两种可能。

方法一、XSD工具


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

  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

就是这样!您已经从 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转换器:单击

于 2013-10-26T21:44:57.970 回答
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;
}
于 2016-12-14T11:47:23.267 回答
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
于 2013-10-29T01:35:25.937 回答
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

于 2021-10-22T16:10:00.900 回答
0

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

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

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

参考:此链接上的更多详细步骤

于 2017-08-08T01:44:15.733 回答