C#實(shí)現(xiàn)XML與實(shí)體類之間相互轉(zhuǎn)換的方法(序列化與反序列化)
本文實(shí)例講述了C#實(shí)現(xiàn)XML與實(shí)體類之間相互轉(zhuǎn)換的方法。分享給大家供大家參考,具體如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
/// <summary>
/// Xml序列化與反序列化
/// </summary>
public class XmlUtil
{
#region 反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">類型</param>
/// <param name="xml">XML字符串</param>
/// <returns></returns>
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception e)
{
return null;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
#endregion
#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">類型</param>
/// <param name="obj">對(duì)象</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化對(duì)象
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
}
/* 實(shí)體對(duì)象轉(zhuǎn)換到Xml */
public class Student
{
public string Name { set; get; }
public int Age { set; get; }
}
Student stu1 = new Student() { Name = "okbase", Age = 10 };
string xml = XmlUtil.Serializer(typeof(Student), stu1);
Console.Write(xml);
/* Xml轉(zhuǎn)換到實(shí)體對(duì)象 */
Student stu2 = XmlUtil.Deserialize(typeof(Student), xml) as Student;
Console.Write(string.Format("名字:{0},年齡:{1}", stu2.Name, stu2.Age));
/* DataTable轉(zhuǎn)換到Xml */
// 生成DataTable對(duì)象用于測(cè)試
DataTable dt1 = new DataTable("mytable"); // 必須指明DataTable名稱
dt1.Columns.Add("Dosage", typeof(int));
dt1.Columns.Add("Drug", typeof(string));
dt1.Columns.Add("Patient", typeof(string));
dt1.Columns.Add("Date", typeof(DateTime));
// 添加行
dt1.Rows.Add(25, "Indocin", "David", DateTime.Now);
dt1.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
dt1.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
dt1.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
dt1.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
// 序列化
xml = XmlUtil.Serializer(typeof(DataTable), dt1);
Console.Write(xml);
/* Xml轉(zhuǎn)換到DataTable */
// 反序列化
DataTable dt2 = XmlUtil.Deserialize(typeof(DataTable), xml) as DataTable;
// 輸出測(cè)試結(jié)果
foreach (DataRow dr in dt2.Rows)
{
foreach (DataColumn col in dt2.Columns)
{
Console.Write(dr[col].ToString() + " ");
}
Console.Write("\r\n");
}
/* List轉(zhuǎn)換到Xml */
// 生成List對(duì)象用于測(cè)試
List<Student> list1 = new List<Student>(3);
list1.Add(new Student() { Name = "okbase", Age = 10 });
list1.Add(new Student() { Name = "csdn", Age = 15 });
// 序列化
xml = XmlUtil.Serializer(typeof(List<Student>), list1);
Console.Write(xml);
/* Xml轉(zhuǎn)換到List */
List<Student> list2 = XmlUtil.Deserialize(typeof(List<Student>), xml) as List<Student>;
foreach (Student stu in list2)
{
Console.WriteLine(stu.Name + "," + stu.Age.ToString());
}
protected void Page_Load(object sender, EventArgs e)
{
string strTest = @"<Relationships>
<VariationParent xmlns='http://www.microsoft.com/schema/Products/2011-10-01'>
<Identifiers>
<MarketplaceASIN>
<MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
<ASIN>B00K69WURQ</ASIN>
</MarketplaceASIN>
<MarketplaceASIN>
<MarketplaceId>TBVPDKIKX0DER</MarketplaceId>
<ASIN>C00K69WURQ</ASIN>
</MarketplaceASIN>
<MarketplaceASIN>
<MarketplaceId>KlVPDKIKX0DER</MarketplaceId>
<ASIN>D00K69WURQ</ASIN>
</MarketplaceASIN>
</Identifiers>
</VariationParent>
</Relationships>";
TextBox1.Text = "";
XmlDocument doc = new XmlDocument();
doc.LoadXml(strTest);
XmlElement root = doc.DocumentElement;
//用于帶命名空間的XML操作
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ab", "http://www.microsoft.com/schema/Products/2011-10-01");
XmlNodeList macthNodes = root.SelectNodes("http://ab:Identifiers/ab:MarketplaceASIN", nsmgr);
for (int i = 0; i < macthNodes.Count; i++)
{
//刪除生成的命名空間,生成標(biāo)準(zhǔn)XML。
string matchNode = CleanXmlnsTag(macthNodes[i].OuterXml);
MarketplaceASIN ma = XmlUtil.Deserialize(typeof(MarketplaceASIN), matchNode) as MarketplaceASIN;
if (ma != null)
{
Response.Write(ma.MarketplaceId + "---------" + ma.ASIN + "<br/>");
}
}
}
/* 實(shí)體對(duì)象 */
public class MarketplaceASIN
{
public string MarketplaceId { set; get; }
public string ASIN { set; get; }
}
protected string CleanXmlnsTag(string xml)
{
xml = xml.Replace("xmlns=\"http://www.microsoft.com/schema/Products/2011-10-01\"", "");
return xml;
}
PS:小編這里再來為大家推薦幾款關(guān)于xml操作的在線工具供大家免費(fèi)使用。相信在以后開發(fā)中可以用的到:
在線XML格式化/壓縮工具:
http://tools.jb51.net/code/xmlformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
xml代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
HTML/XML轉(zhuǎn)義字符對(duì)照表:
http://tools.jb51.net/table/html_escape
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#中XML文件操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》及《C#程序設(shè)計(jì)之線程使用技巧總結(jié)》
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
- C#實(shí)現(xiàn)XML序列化與反序列化
- C#對(duì)Json進(jìn)行序列化和反序列化
- C#中關(guān)于序列化與反序列化的三種方法
- C# 解析XML和反序列化的示例
- C# Newtonsoft.Json 解析多嵌套json 進(jìn)行反序列化的實(shí)例
- C#中Json反序列化的實(shí)現(xiàn)方法
- C#序列化與反序列化(Serialize,Deserialize)實(shí)例詳解
- c#對(duì)象反序列化與對(duì)象序列化示例詳解
- C#實(shí)現(xiàn)json的序列化和反序列化實(shí)例代碼
- 深入理解C#序列化與反序列化的詳解
- C# SimpleJSON字典反序列化實(shí)戰(zhàn)教程
相關(guān)文章
C#語(yǔ)句先后順序?qū)Τ绦虻慕Y(jié)果有影響嗎
有朋友問我,C#中C#語(yǔ)句先后順序影響程序的結(jié)果嗎?告訴大家,答案是肯定的,絕對(duì)影響程序的結(jié)果,所以在程序中一定要注意C#語(yǔ)句的順序2015-10-10
C#使用晚綁定來實(shí)現(xiàn)壓縮Access數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了C#使用晚綁定來實(shí)現(xiàn)壓縮Access數(shù)據(jù)庫(kù)的方法,項(xiàng)目開發(fā)中有一定的實(shí)用價(jià)值,需要的朋友可以參考下2014-08-08
C#8.0 中開啟默認(rèn)接口實(shí)現(xiàn)方法
這篇文章主要介紹了C#8.0 中開啟默認(rèn)接口實(shí)現(xiàn)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧的相關(guān)資料2019-05-05
c#調(diào)用api控制windows關(guān)機(jī)示例(可以重啟/注銷)
本文介紹了c#控制windows關(guān)機(jī)、重啟、注銷的二種方法,分為調(diào)用windows自帶的shutdown.exe關(guān)機(jī)和調(diào)用API關(guān)機(jī)的方法2014-01-01
C#后臺(tái)調(diào)用前臺(tái)JS函數(shù)方法
今天小編就為大家分享一篇關(guān)于C#后臺(tái)調(diào)用前臺(tái)JS函數(shù)方法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
C#中使用ADOMD.NET查詢多維數(shù)據(jù)集的實(shí)現(xiàn)方法
這篇文章主要介紹了C#中使用ADOMD.NET查詢多維數(shù)據(jù)集的實(shí)現(xiàn)方法,詳細(xì)講述了C#中使用ADOMD.NET查詢多維數(shù)據(jù)集的原理與實(shí)現(xiàn)技巧,需要的朋友可以參考下2014-10-10
WPF ProgressBar實(shí)現(xiàn)實(shí)時(shí)進(jìn)度效果
這篇文章主要介紹了WPF ProgressBar實(shí)現(xiàn)實(shí)時(shí)進(jìn)度效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12

