摘要:XML的讀寫
讀入XML格式的檔案,並可寫入,前人所寫的,先copy下來~
using System;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Linq;
namespace ShaLu.Undertaker
{
/// <summary>
/// XML 的摘要描述。
/// </summary>
public class XML
{
private XmlDocument xmlDoc=new XmlDocument();
private string XMLFileName="";
public XML()
{
//Constructor
}
public XML(string FName)
{
this.FileName=FName;
}
public string FileName
{
#region 設定檔名
set{XMLFileName=value;}
get{return XMLFileName;}
#endregion
}
public void LoadXML(string FileName)
{
#region 載入XML檔案
try
{
xmlDoc.Load(FileName);
}
catch(IOException ioex)
{
Console.WriteLine(ioex.ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
#endregion
}
public void LoadXML()
{
#region 載入XML檔案
try
{
xmlDoc.Load(this.FileName);
}
catch(IOException ioex)
{
Console.WriteLine(ioex.ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
#endregion
}
public string GetNodeValue(string ParentName,string NodeName)
{
#region 取得節點
string ReturnValue="";
XmlNodeList nodeList=xmlDoc.SelectSingleNode(ParentName).ChildNodes;//獲取Parent節點的所有子節點
foreach(XmlNode xn in nodeList)//遍歷所有子節點
{
XmlElement xe=(XmlElement)xn;//將子節點類型轉換為XmlElement類型
if(xe.Name==NodeName)//取得指定節點的資料
{
ReturnValue=xe.InnerText;
break;
}
}
//檢查一下印表機 囧,以免xml設定的是錯誤的印表機會發生錯誤XD add by Tim Yang at 2010/1/28
if (NodeName == "Certificate")
{
bool b = false;
var ipc = PrinterSettings.InstalledPrinters;
foreach(string name in ipc)
if (name == ReturnValue)
{
b = true;
break;
}
if(!b)
{
if (ipc.Count > 0)
ReturnValue = ipc[0];
else
MessageBox.Show("此電腦未安裝任何印表機!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return ReturnValue;
#endregion
}
public void WriteNodeValue(string ParentName,string NodeName,string NodeValue)
{
#region 找到指定的節點,並將資料寫入
XmlNodeList nodeList=xmlDoc.SelectSingleNode(ParentName).ChildNodes;//獲取Configure節點的所有子節點
foreach(XmlNode xn in nodeList)//遍歷所有子節點
{
XmlElement xe=(XmlElement)xn;//將子節點類型轉換為XmlElement類型
if(xe.Name==NodeName)//取得指定節點的資料
{
xe.InnerText=NodeValue;
break;
}
}
#endregion
}
public void SaveXML(string FName)
{
#region 將XML存入
xmlDoc.Save(FName);
#endregion
}
public void SaveXML()
{
#region 將XML存入
xmlDoc.Save(this.FileName);
#endregion
}
public void Dispose()
{
#region 終結掉
this.Dispose(true);
GC.SuppressFinalize(this);
#endregion
}
protected virtual void Dispose(bool isDispose)
{
#region 準備釋放資源
if(!isDispose)
{
this.xmlDoc=null;
}
else
{
return;
}
#endregion
}
}
}