XML序列化、反序列化、節點等操作類輔助類 XmlHelper
實現效果
本輔助類主要是用來方便實現XML序列化、反序列化、節點等操作。
序列化是指一個對象的實例可以被保存,保存成一個二進制串或者XML等格式字符串。反序列化這是從這些內容中還原為一個對象實例的操作。
要實現對象的序列化,首先要保證該對象可以序列化。而且,序列化只是將對象的屬性進行有效的保存,對於對象的一些方法則無法實現序列化的。
實現一個類可序列化的最簡便的方法就是增加Serializable屬性標記類。
實現步驟
在代碼引用相關的代碼實現動態調用。
實現代碼
輔助類提供的方法接口如下所示:
/// 構造函數
public XmlHelper(string XmlFile)
#region 靜態方法
/// 二進制序列化
public static bool Serialize(string path, object obj)
/// XML序列化
public static bool XmlSerialize(string path, object obj, Type type)
/// 二進制反序列化
public static object Deserialize(string path)
/// XML反序列化
public static object XmlDeserialize(string path, Type type)
#endregion
#region 公用方法
/// 獲取指定節點下面的XML子節點
public XmlNodeList Read(string XmlPathNode)
/// 讀取節點屬性內容
public string Read(string XmlPathNode, string Attrib)
/// 獲取元素節點對象
public XmlElement GetElement(string XmlPathNode, string elementName)
/// 獲取元素節點的值
public string GetElementData(string XmlPathNode, string elementName)
/// 獲取節點下的DataSet
public DataSet GetData(string XmlPathNode)
/// 替換某節點的內容
public void Replace(string XmlPathNode, string Content)
/// 刪除節點
public void Delete(string Node)
/// 插入一節點和此節點的一子節點
public void InsertNode(string MainNode, string ChildNode, string Element, string Content)
/// 插入一個節點帶一個屬性
public void InsertElement(string MainNode, string Element, string Attrib, string AttribContent, string Content)
/// 插入XML元素
public void InsertElement(string MainNode, string Element, string Content)
/// 保存XML文檔
public void Save()
輔助類XmlHelper的使用例子代碼如下所示
SearchInfo searchInfo = new SearchInfo();
searchInfo.FieldName = "TestFeild";
searchInfo.FieldValue = "TestValue";
string file = @"C:\searchInfo.xml";
XmlHelper.XmlSerialize(file, searchInfo, typeof(SearchInfo));
SearchInfo info2FromXml = XmlHelper.XmlDeserialize(file, typeof(SearchInfo)) as SearchInfo;
Console.WriteLine("{0} : {0}", info2FromXml.FieldName, info2FromXml.FieldValue);
輔助類XmlHelper操作節點的例子代碼如下所示
//bookstore.xml文件內容
/*
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="it" ISBN="9787302461968">
<title>C#高級編程</title>
<author>Christian Nagel</author>
<price>132.0</price>
</book>
</bookstore>
*/
string file = @"c:\bookstore.xml";
XmlHelper helper = new XmlHelper(file);
string value = helper.Read("bookstore/book", "genre");
Console.WriteLine(value);//it
value = helper.Read("bookstore/book", "ISBN");
Console.WriteLine(value);//9787302461968
value = helper.GetElementData("bookstore/book", "title");
Console.WriteLine(value);//C#高級編程
XmlElement element = helper.GetElement("bookstore/book", "title");
element.InnerText = "程序員老郭";
DataSet ds = helper.GetData("bookstore/book");
ds.WriteXml(@"C:\ds.xml");