首先將XML資料內容複製貼上至Xml2CSharp.com。
點選底下的Convert,產生結果。
在專案建立Models資料夾與Orgs.cs。
複製結果,貼到Orgs.cs,調整程式碼:
using System.Collections.Generic;
using System.Xml.Serialization;
namespace xml2.Models
{
[XmlRoot(ElementName = "orgs")]
public class Orgs
{
[XmlElement(ElementName = "frg")]
public Frg Frg { get; set; }
}
[XmlRoot(ElementName = "frg")]
public class Frg
{
[XmlElement(ElementName = "org")]
public List<Org> Org { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlRoot(ElementName = "org")]
public class Org
{
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "lat")]
public string Lat { get; set; }
[XmlAttribute(AttributeName = "lng")]
public string Lng { get; set; }
[XmlAttribute(AttributeName = "informaddress")]
public string Informaddress { get; set; }
[XmlAttribute(AttributeName = "hlink")]
public string Hlink { get; set; }
[XmlAttribute(AttributeName = "informtel")]
public string Informtel { get; set; }
[XmlAttribute(AttributeName = "servItem")]
public string ServItem { get; set; }
[XmlAttribute(AttributeName = "servTime")]
public string ServTime { get; set; }
[XmlAttribute(AttributeName = "dataOrg")]
public string DataOrg { get; set; }
[XmlAttribute(AttributeName = "doOrg")]
public string DoOrg { get; set; }
[XmlText]
public string Text { get; set; }
}
}
Model建立完成。
Program.cs
static void Main(string[] args)
{
var program = new Program();
program.ReadPO(@"C:\frg.xml");
}
private void ReadPO(string filename)
{
// 建立serializer物件,並指定反序列化物件的型別
XmlSerializer serializer = new XmlSerializer(typeof(Orgs));
// 宣告一個要被反序列化的型別的物件變數
Orgs orgs;
// 建立FileStream物件,讀取XML檔案
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
//反序列化XML
orgs = (Orgs)serializer.Deserialize(fs);
}
Console.Write(orgs.Frg.Org);
}
下中斷點確認是否有轉換成物件型別:
參考來源:
XmlSerializer Class (System.Xml.Serialization) | Microsoft Docs
VS 2015後可以直接貼JSON和XML轉成CLASS
[VisualStudio] Paste Special - 將 Json 或 XML 文字轉換為 C# 類別物件 m@rcus 學習筆記
感謝補充,這個方式我知道,剛好看到這個網站有提供類似的功能,做個筆記。