迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 >

在 C# 中将 XML 反序列化为对象

作者:迹忆客 最近更新:2024/02/01 浏览次数:

本文将演示将 XML 文件转换或反序列化为 C# 对象。


使用手动类型的类将 XML 文件反序列化为 C# 对象

  • C# 与 classesobjects 以及 attributesmethods 相关联。
  • Objects 以编程方式用类表示,例如 JohnJames
  • 属性是对象的特征,例如汽车的颜色生产年份人的年龄建筑物的颜色
  • XML 是允许解析 XML 数据而不考虑传输 XML 文件的媒介的标准化格式。

下面是一个将转换为 C# 对象的 XML 代码示例。

1. <?xml version="1.0" encoding="utf-8"?>
2. <Company xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema">
3.  <Employee name="x" age="30" />
4.  <Employee name="y" age="32" />
5. </Company>

将在 C# 中创建具有类似结构的类来转换 XML 代码示例。

using System.Xml.Serialization;

[XmlRoot(ElementName = "Company")]
public class Company

{
  public Company() {
    Employees = new List<Employee>();
  }

  [XmlElement(ElementName = "Employee")]
  public List<Employee> Employees { get; set; }

  public Employee this[string name] {
    get {
      return Employees.FirstOrDefault(
          s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase));
    }
  }
}

public class Employee {
  [XmlAttribute("name")]
  public string Name { get; set; }

  [XmlAttribute("age")]
  public string Age { get; set; }
}

XML 对象转换为 C# 的最后一步是使用 System.Xml.Serialization.XmlSerializer 函数来序列化对象。

public T DeserializeToObject<T>(string filepath)
    where T : class {
  System.Xml.Serialization.XmlSerializer ser =
      new System.Xml.Serialization.XmlSerializer(typeof(T));

  using (StreamReader sr = new StreamReader(filepath)) {
    return (T)ser.Deserialize(sr);
  }
}

使用 Visual Studio 的 Paste Special 功能将 Xml 反序列化为 C# 对象

此方法需要使用 Microsoft Visual Studio 2012 及更高版本和 .Net Framework 4.5 及更高版本。还必须安装 Visual Studio 的 WCF 工作负载。

  • XML 文档的内容必须复制到剪贴板。
  • 在项目解决方案中添加一个新的 empty 类。
  • 打开新的类文件。
  • 单击 IDE 菜单栏上的 Edit 按钮。
  • 从下拉列表中选择 Paste Special
  • 单击 Paste XML As Classes

 

要使用 Visual Studio 生成的类,请创建 Helpers 类。

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

使用 XSD 工具XML 反序列化为 C# 对象

XSD 用于自动生成与 XML 文件或文档中定义的模式等效的 classesobjects

XSD.exe 通常在以下路径中找到:C:\Program Files (x86)\Microsoft SDKs\Windows\{version}\bin\NETFX {version} Tools\

假设 XML 文件保存在此路径中:C:\X\test.XML

以下是将 XML 自动反序列化为 C# 类的步骤:

  • 在搜索栏中键入开发人员命令提示符并单击它以打开。
  • 键入 cd C:\X 导航到 XML 文件路径。
  • 删除 XML 文件中的行号和任何不必要的字符。
  • 键入 xsd test.XML 从 test.XML 创建一个等效的 XSD 文件
  • 在同一文件路径中创建一个 test.XSD 文件。
  • 键入 XSD /c test.XSD 创建与 XML 文件等效的 C# classes
  • 创建一个 test.cs 文件,一个具有 XML 文件的精确模式的 C# 类。

输出:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.8.3928.0.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Company {

    private CompanyEmployee[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Employee", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public CompanyEmployee[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CompanyEmployee {

    private string nameField;

    private string ageField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string age {
        get {
            return this.ageField;
        }
        set {
            this.ageField = value;
        }
    }
}

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 C# 中发出 HTTP POST Web 请求

发布时间:2024/02/04 浏览次数:131 分类:编程语言

在 C# 中,可以使用 3 种主要方法来发出 HTTP POST Web 请求:WebClient 类,HttpWebRequest 类和 HttpClient 类。本教程将讨论在 C# 中发出 HTTP POST Web 请求的方法。使用 C# 中的 WebClient 类发出 HTTP POST Web 请求

在 C# 中调整图像大小

发布时间:2024/02/04 浏览次数:203 分类:编程语言

有两种主要方法可用于在 C# 中调整图像的大小,Bitmap 类构造函数和 graphics.DrawImage()函数。在本教程中,我们将讨论在C#中调整图像大小的方法。我们将带您完成整个过程,从加载原始图像到保

在 C# 中下载图片

发布时间:2024/02/04 浏览次数:138 分类:编程语言

有 3 种主要方法可用于下载 C# 中的图片,WebClient.DownloadFile()函数,Bitmap 类和 Image.FromStream()函数。在 C# 中使用 WebClient 类下载图片 WebClient 类提供了用于向 C# 中的 URL 发送数据和从 URL 接收数据

在 C# 中使用秒表

发布时间:2024/02/04 浏览次数:139 分类:编程语言

我们可以使用 Stopwatch 类来计算 C# 中的经过时间。使用 C# 中的秒表类计算经过时间 Stopwatch 类在 C# 中准确测量经过的时间。

在 C# 中获取可执行路径

发布时间:2024/02/04 浏览次数:200 分类:编程语言

有 3 种主要方法可用于获取 C# 中程序的可执行路径,即 Assembly 类,AppDomain 类和 Path 类。本教程将介绍获取 C# 代码的可执行路径的方法。使用 C# 中的 Assembly 类获取可执行路径

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便