C#對(duì)XmlHelper幫助類操作Xml文檔的通用方法匯總
前言
該篇文章主要總結(jié)的是自己平時(shí)工作中使用頻率比較高的Xml文檔操作的一些常用方法和收集網(wǎng)上寫的比較好的一些通用Xml文檔操作的方法(主要包括Xml序列化和反序列化,Xml文件讀取,Xml文檔節(jié)點(diǎn)內(nèi)容增刪改的一些通過(guò)方法)。當(dāng)然可能還有很多方法會(huì)漏了,假如各位同學(xué)好的方法可以在文末留言,我會(huì)統(tǒng)一收集起來(lái)。
C#XML基礎(chǔ)入門
http://www.dbjr.com.cn/article/104113.htm
Xml反序列化為對(duì)象
#region Xml反序列化為對(duì)象
/// <summary>
/// Xml反序列化為指定模型對(duì)象
/// </summary>
/// <typeparam name="T">對(duì)象類型</typeparam>
/// <param name="xmlContent">Xml內(nèi)容</param>
/// <param name="isThrowException">是否拋出異常</param>
/// <returns></returns>
public static T XmlConvertToModel<T>(string xmlContent, bool isThrowException = false) where T : class
{
StringReader stringReader = null;
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
stringReader = new StringReader(xmlContent);
return (T)xmlSerializer.Deserialize(stringReader);
}
catch (Exception ex)
if (isThrowException)
{
throw ex;
}
return null;
finally
stringReader?.Dispose();
}
/// <summary>
/// 讀取Xml文件內(nèi)容反序列化為指定的對(duì)象
/// </summary>
/// <param name="filePath">Xml文件的位置(絕對(duì)路徑)</param>
/// <returns></returns>
public static T DeserializeFromXml<T>(string filePath)
if (!File.Exists(filePath))
throw new ArgumentNullException(filePath + " not Exists");
using (StreamReader reader = new StreamReader(filePath))
XmlSerializer xs = new XmlSerializer(typeof(T));
T ret = (T)xs.Deserialize(reader);
return ret;
return default(T);
#endregion對(duì)象序列化為Xml
#region 對(duì)象序列化為Xml
/// <summary>
/// 對(duì)象序列化為Xml
/// </summary>
/// <param name="obj">對(duì)象</param>
/// <param name="isThrowException">是否拋出異常</param>
/// <returns></returns>
public static string ObjectSerializerXml<T>(T obj, bool isThrowException = false)
{
if (obj == null)
{
return string.Empty;
}
try
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
//強(qiáng)制指定命名空間,覆蓋默認(rèn)的命名空間
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
//在Xml序列化時(shí)去除默認(rèn)命名空間xmlns:xsd和xmlns:xsi
namespaces.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
//序列化時(shí)增加namespaces
serializer.Serialize(sw, obj, namespaces);
sw.Close();
string replaceStr = sw.ToString().Replace(@"<?xml version=""1.0"" encoding=""utf-16""?>", "");
return replaceStr;
}
catch (Exception ex)
if (isThrowException)
throw ex;
}
#endregionXml字符處理
#region Xml字符處理
/// <summary>
/// 特殊符號(hào)轉(zhuǎn)換為轉(zhuǎn)義字符
/// </summary>
/// <param name="xmlStr"></param>
/// <returns></returns>
public string XmlSpecialSymbolConvert(string xmlStr)
{
return xmlStr.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\'", "'").Replace("\"", """);
}
#endregion創(chuàng)建Xml文檔
#region 創(chuàng)建Xml文檔
/// <summary>
/// 創(chuàng)建Xml文檔
/// </summary>
/// <param name="saveFilePath">文件保存位置</param>
public void CreateXmlDocument(string saveFilePath)
{
XmlDocument xmlDoc = new XmlDocument();
//創(chuàng)建類型聲明節(jié)點(diǎn)
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//創(chuàng)建Xml根節(jié)點(diǎn)
XmlNode root = xmlDoc.CreateElement("books");
xmlDoc.AppendChild(root);
XmlNode root1 = xmlDoc.CreateElement("book");
root.AppendChild(root1);
//創(chuàng)建子節(jié)點(diǎn)
CreateNode(xmlDoc, root1, "author", "追逐時(shí)光者");
CreateNode(xmlDoc, root1, "title", "XML學(xué)習(xí)教程");
CreateNode(xmlDoc, root1, "publisher", "時(shí)光出版社");
//將文件保存到指定位置
xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/);
}
/// <summary>
/// 創(chuàng)建節(jié)點(diǎn)
/// </summary>
/// <param name="xmlDoc">xml文檔</param>
/// <param name="parentNode">Xml父節(jié)點(diǎn)</param>
/// <param name="name">節(jié)點(diǎn)名</param>
/// <param name="value">節(jié)點(diǎn)值</param>
///
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
//創(chuàng)建對(duì)應(yīng)Xml節(jié)點(diǎn)元素
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
#endregionXml數(shù)據(jù)讀取
#region Xml數(shù)據(jù)讀取
/// <summary>
/// 讀取Xml指定節(jié)點(diǎn)中的數(shù)據(jù)
/// </summary>
/// <param name="filePath">Xml文檔路徑</param>
/// <param name="node">節(jié)點(diǎn)</param>
/// <param name="attribute">讀取數(shù)據(jù)的屬性名</param>
/// <returns>string</returns>
/**************************************************
* 使用示列:
* XmlHelper.XmlReadNodeAttributeValue(path, "/books/book", "author")
************************************************/
public static string XmlReadNodeAttributeValue(string filePath, string node, string attribute)
{
string value = "";
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xmlNode = doc.SelectSingleNode(node);
value = (attribute.Equals("") ? xmlNode.InnerText : xmlNode.Attributes[attribute].Value);
}
catch { }
return value;
}
/// 獲得xml文件中指定節(jié)點(diǎn)的節(jié)點(diǎn)數(shù)據(jù)
/// <param name="nodeName">節(jié)點(diǎn)名</param>
/// <returns></returns>
public static string GetNodeInfoByNodeName(string filePath, string nodeName)
string XmlString = string.Empty;
XmlDocument xml = new XmlDocument();
xml.Load(filePath);
XmlElement root = xml.DocumentElement;
XmlNode node = root.SelectSingleNode("http://" + nodeName);
if (node != null)
XmlString = node.InnerText;
return XmlString;
/// 獲取某一節(jié)點(diǎn)的所有孩子節(jié)點(diǎn)的值
/// <param name="node">要查詢的節(jié)點(diǎn)</param>
public string[] ReadAllChildallValue(string node, string filePath)
int i = 0;
string[] str = { };
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(node);
XmlNodeList nodelist = xn.ChildNodes; //得到該節(jié)點(diǎn)的子節(jié)點(diǎn)
if (nodelist.Count > 0)
str = new string[nodelist.Count];
foreach (XmlElement el in nodelist)//讀元素值
{
str[i] = el.Value;
i++;
}
return str;
public XmlNodeList ReadAllChild(string node, string filePath)
return nodelist;
#endregionXml插入數(shù)據(jù)
#region Xml插入數(shù)據(jù)
/// <summary>
/// Xml指定節(jié)點(diǎn)元素屬性插入數(shù)據(jù)
/// </summary>
/// <param name="path">路徑</param>
/// <param name="node">節(jié)點(diǎn)</param>
/// <param name="element">元素名</param>
/// <param name="attribute">屬性名</param>
/// <param name="value">屬性數(shù)據(jù)</param>
/// <returns></returns>
/**************************************************
* 使用示列:
* XmlHelper.XmlInsertValue(path, "/books", "book", "author", "Value")
************************************************/
public static void XmlInsertValue(string path, string node, string element, string attribute, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode xmlNode = doc.SelectSingleNode(node);
if (element.Equals(""))
{
if (!attribute.Equals(""))
{
XmlElement xe = (XmlElement)xmlNode;
xe.SetAttribute(attribute, value);
}
}
else
XmlElement xe = doc.CreateElement(element);
if (attribute.Equals(""))
xe.InnerText = value;
else
//添加新增的節(jié)點(diǎn)
xmlNode.AppendChild(xe);
//保存Xml文檔
doc.Save(path);
}
catch { }
}
#endregionXml修改數(shù)據(jù)
#region Xml修改數(shù)據(jù)
/// <summary>
/// Xml指定節(jié)點(diǎn)元素屬性修改數(shù)據(jù)
/// </summary>
/// <param name="path">路徑</param>
/// <param name="node">節(jié)點(diǎn)</param>
/// <param name="attribute">屬性名</param>
/// <param name="value">屬性數(shù)據(jù)</param>
/// <returns></returns>
/**************************************************
* 使用示列:
* XmlHelper.XmlUpdateValue(path, "/books", "book","author","Value")
************************************************/
public static void XmlUpdateValue(string path, string node, string attribute, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode xmlNode = doc.SelectSingleNode(node);
XmlElement xmlElement = (XmlElement)xmlNode;
if (attribute.Equals(""))
xmlElement.InnerText = value;
else
xmlElement.SetAttribute(attribute, value);
//保存Xml文檔
doc.Save(path);
}
catch { }
}
#endregionXml刪除數(shù)據(jù)
#region Xml刪除數(shù)據(jù)
/// <summary>
/// 刪除數(shù)據(jù)
/// </summary>
/// <param name="path">路徑</param>
/// <param name="node">節(jié)點(diǎn)</param>
/// <param name="attribute">屬性名</param>
/// <returns></returns>
/**************************************************
* 使用示列:
* XmlHelper.XmlDelete(path, "/books", "book")
************************************************/
public static void XmlDelete(string path, string node, string attribute)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode xn = doc.SelectSingleNode(node);
XmlElement xe = (XmlElement)xn;
if (attribute.Equals(""))
xn.ParentNode.RemoveChild(xn);
else
xe.RemoveAttribute(attribute);
doc.Save(path);
}
catch { }
}
#endregion完整的XmlHelper幫助類
注意:有些方法不能保證百分之百?zèng)]有問(wèn)題的,假如有問(wèn)題可以留言給我,我會(huì)驗(yàn)證并立即修改。
/// <summary>
/// Xml幫助類
/// </summary>
public class XMLHelper
{
#region Xml反序列化為對(duì)象
/// <summary>
/// Xml反序列化為指定模型對(duì)象
/// </summary>
/// <typeparam name="T">對(duì)象類型</typeparam>
/// <param name="xmlContent">Xml內(nèi)容</param>
/// <param name="isThrowException">是否拋出異常</param>
/// <returns></returns>
public static T XmlConvertToModel<T>(string xmlContent, bool isThrowException = false) where T : class
{
StringReader stringReader = null;
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
stringReader = new StringReader(xmlContent);
return (T)xmlSerializer.Deserialize(stringReader);
}
catch (Exception ex)
if (isThrowException)
{
throw ex;
}
return null;
finally
stringReader?.Dispose();
}
/// <summary>
/// 讀取Xml文件內(nèi)容反序列化為指定的對(duì)象
/// </summary>
/// <param name="filePath">Xml文件的位置(絕對(duì)路徑)</param>
/// <returns></returns>
public static T DeserializeFromXml<T>(string filePath)
if (!File.Exists(filePath))
throw new ArgumentNullException(filePath + " not Exists");
using (StreamReader reader = new StreamReader(filePath))
XmlSerializer xs = new XmlSerializer(typeof(T));
T ret = (T)xs.Deserialize(reader);
return ret;
return default(T);
#endregion
#region 對(duì)象序列化為Xml
/// 對(duì)象序列化為Xml
/// <param name="obj">對(duì)象</param>
public static string ObjectSerializerXml<T>(T obj, bool isThrowException = false)
if (obj == null)
return string.Empty;
using (StringWriter sw = new StringWriter())
Type t = obj.GetType();
//強(qiáng)制指定命名空間,覆蓋默認(rèn)的命名空間
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
//在Xml序列化時(shí)去除默認(rèn)命名空間xmlns:xsd和xmlns:xsi
namespaces.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
//序列化時(shí)增加namespaces
serializer.Serialize(sw, obj, namespaces);
sw.Close();
string replaceStr = sw.ToString().Replace(@"<?xml version=""1.0"" encoding=""utf-16""?>", "");
return replaceStr;
#region Xml字符處理
/// 特殊符號(hào)轉(zhuǎn)換為轉(zhuǎn)義字符
/// <param name="xmlStr"></param>
public string XmlSpecialSymbolConvert(string xmlStr)
return xmlStr.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\'", "'").Replace("\"", """);
#region 創(chuàng)建Xml文檔
/// 創(chuàng)建Xml文檔
/// <param name="saveFilePath">文件保存位置</param>
public void CreateXmlDocument(string saveFilePath)
XmlDocument xmlDoc = new XmlDocument();
//創(chuàng)建類型聲明節(jié)點(diǎn)
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//創(chuàng)建Xml根節(jié)點(diǎn)
XmlNode root = xmlDoc.CreateElement("books");
xmlDoc.AppendChild(root);
XmlNode root1 = xmlDoc.CreateElement("book");
root.AppendChild(root1);
//創(chuàng)建子節(jié)點(diǎn)
CreateNode(xmlDoc, root1, "author", "追逐時(shí)光者");
CreateNode(xmlDoc, root1, "title", "XML學(xué)習(xí)教程");
CreateNode(xmlDoc, root1, "publisher", "時(shí)光出版社");
//將文件保存到指定位置
xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/);
/// <summary>
/// 創(chuàng)建節(jié)點(diǎn)
/// <param name="xmlDoc">xml文檔</param>
/// <param name="parentNode">Xml父節(jié)點(diǎn)</param>
/// <param name="name">節(jié)點(diǎn)名</param>
/// <param name="value">節(jié)點(diǎn)值</param>
///
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
//創(chuàng)建對(duì)應(yīng)Xml節(jié)點(diǎn)元素
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
#region Xml數(shù)據(jù)讀取
/// 讀取Xml指定節(jié)點(diǎn)中的數(shù)據(jù)
/// <param name="filePath">Xml文檔路徑</param>
/// <param name="node">節(jié)點(diǎn)</param>
/// <param name="attribute">讀取數(shù)據(jù)的屬性名</param>
/// <returns>string</returns>
/**************************************************
* 使用示列:
* XmlHelper.XmlReadNodeAttributeValue(path, "/books/book", "author")
************************************************/
public static string XmlReadNodeAttributeValue(string filePath, string node, string attribute)
string value = "";
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xmlNode = doc.SelectSingleNode(node);
value = (attribute.Equals("") ? xmlNode.InnerText : xmlNode.Attributes[attribute].Value);
catch { }
return value;
/// 獲得xml文件中指定節(jié)點(diǎn)的節(jié)點(diǎn)數(shù)據(jù)
/// <param name="nodeName">節(jié)點(diǎn)名</param>
public static string GetNodeInfoByNodeName(string filePath, string nodeName)
string XmlString = string.Empty;
XmlDocument xml = new XmlDocument();
xml.Load(filePath);
XmlElement root = xml.DocumentElement;
XmlNode node = root.SelectSingleNode("http://" + nodeName);
if (node != null)
XmlString = node.InnerText;
return XmlString;
/// 獲取某一節(jié)點(diǎn)的所有孩子節(jié)點(diǎn)的值
/// <param name="node">要查詢的節(jié)點(diǎn)</param>
public string[] ReadAllChildallValue(string node, string filePath)
int i = 0;
string[] str = { };
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(node);
XmlNodeList nodelist = xn.ChildNodes; //得到該節(jié)點(diǎn)的子節(jié)點(diǎn)
if (nodelist.Count > 0)
str = new string[nodelist.Count];
foreach (XmlElement el in nodelist)//讀元素值
str[i] = el.Value;
i++;
return str;
public XmlNodeList ReadAllChild(string node, string filePath)
return nodelist;
#region Xml插入數(shù)據(jù)
/// Xml指定節(jié)點(diǎn)元素屬性插入數(shù)據(jù)
/// <param name="path">路徑</param>
/// <param name="element">元素名</param>
/// <param name="attribute">屬性名</param>
/// <param name="value">屬性數(shù)據(jù)</param>
* XmlHelper.XmlInsertValue(path, "/books", "book", "author", "Value")
public static void XmlInsertValue(string path, string node, string element, string attribute, string value)
doc.Load(path);
if (element.Equals(""))
if (!attribute.Equals(""))
{
XmlElement xe = (XmlElement)xmlNode;
xe.SetAttribute(attribute, value);
}
else
XmlElement xe = doc.CreateElement(element);
if (attribute.Equals(""))
xe.InnerText = value;
else
//添加新增的節(jié)點(diǎn)
xmlNode.AppendChild(xe);
//保存Xml文檔
doc.Save(path);
#region Xml修改數(shù)據(jù)
/// Xml指定節(jié)點(diǎn)元素屬性修改數(shù)據(jù)
* XmlHelper.XmlUpdateValue(path, "/books", "book","author","Value")
public static void XmlUpdateValue(string path, string node, string attribute, string value)
XmlElement xmlElement = (XmlElement)xmlNode;
if (attribute.Equals(""))
xmlElement.InnerText = value;
xmlElement.SetAttribute(attribute, value);
#region Xml刪除數(shù)據(jù)
/// 刪除數(shù)據(jù)
* XmlHelper.XmlDelete(path, "/books", "book")
public static void XmlDelete(string path, string node, string attribute)
XmlNode xn = doc.SelectSingleNode(node);
XmlElement xe = (XmlElement)xn;
xn.ParentNode.RemoveChild(xn);
xe.RemoveAttribute(attribute);
}到此這篇關(guān)于C#XmlHelper幫助類操作Xml文檔的通用方法匯總的文章就介紹到這了,更多相關(guān)C#XmlHelper幫助類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入分析C#中WinForm控件之Dock順序調(diào)整的詳解
本篇文章是對(duì)C#中WinForm控件之Dock順序調(diào)整進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
DirectoryInfo引用一個(gè)相對(duì)目錄的實(shí)例
這種特殊參數(shù)在Windows的命令提示符或者“運(yùn)行”對(duì)話框中都可以使用,等價(jià)于DOS中的cd命令參數(shù)。直接上代碼,一看你就懂了:2013-04-04
C#ComboBox控件“設(shè)置 DataSource 屬性后無(wú)法修改項(xiàng)集合”的解決方法
這篇文章主要介紹了C#ComboBox控件“設(shè)置 DataSource 屬性后無(wú)法修改項(xiàng)集合”的解決方法 ,需要的朋友可以參考下2019-04-04
C# 關(guān)于LoadLibrary的疑問(wèn)詳解
這篇文章主要介紹了C# 關(guān)于LoadLibrary的疑問(wèn)詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
C#實(shí)現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法,涉及C#針對(duì)json格式數(shù)據(jù)轉(zhuǎn)換的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08

