在 C# 中將 XML 反序列化為物件
    
    Abdullahi Salawudeen
    2023年12月11日
    
    Csharp
    Csharp Object
    
- 使用手動型別的類將 XML 檔案反序列化為 C# 物件
- 
          
            使用 Visual Studio 的 Paste Special功能將Xml反序列化為 C# 物件
- 
          
            使用 XSD 工具將XML反序列化為 C# 物件
 
本文將演示將 XML 檔案轉換或反序列化為 C# 物件。
使用手動型別的類將 XML 檔案反序列化為 C# 物件
- C# 與 classes和objects以及attributes和methods相關聯。
- Objects以程式設計方式用類表示,例如- John或- James。
- 屬性是物件的特徵,例如- 汽車的顏色、- 生產年份、- 人的年齡或- 建築物的顏色。
- 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 檔案或文件中定義的模式等效的 classes 或 objects。
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;
        }
    }
}
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
