C#對XmlHelper幫助類操作Xml文檔的通用方法匯總
前言
該篇文章主要總結(jié)的是自己平時工作中使用頻率比較高的Xml文檔操作的一些常用方法和收集網(wǎng)上寫的比較好的一些通用Xml文檔操作的方法(主要包括Xml序列化和反序列化,Xml文件讀取,Xml文檔節(jié)點內(nèi)容增刪改的一些通過方法)。當(dāng)然可能還有很多方法會漏了,假如各位同學(xué)好的方法可以在文末留言,我會統(tǒng)一收集起來。
C#XML基礎(chǔ)入門
http://chabaoo.cn/article/104113.htm
Xml反序列化為對象
#region Xml反序列化為對象
/// <summary>
/// Xml反序列化為指定模型對象
/// </summary>
/// <typeparam name="T">對象類型</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)容反序列化為指定的對象
/// </summary>
/// <param name="filePath">Xml文件的位置(絕對路徑)</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對象序列化為Xml
#region 對象序列化為Xml
/// <summary>
/// 對象序列化為Xml
/// </summary>
/// <param name="obj">對象</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();
//強制指定命名空間,覆蓋默認的命名空間
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
//在Xml序列化時去除默認命名空間xmlns:xsd和xmlns:xsi
namespaces.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
//序列化時增加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>
/// 特殊符號轉(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é)點
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//創(chuàng)建Xml根節(jié)點
XmlNode root = xmlDoc.CreateElement("books");
xmlDoc.AppendChild(root);
XmlNode root1 = xmlDoc.CreateElement("book");
root.AppendChild(root1);
//創(chuàng)建子節(jié)點
CreateNode(xmlDoc, root1, "author", "追逐時光者");
CreateNode(xmlDoc, root1, "title", "XML學(xué)習(xí)教程");
CreateNode(xmlDoc, root1, "publisher", "時光出版社");
//將文件保存到指定位置
xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/);
}
/// <summary>
/// 創(chuàng)建節(jié)點
/// </summary>
/// <param name="xmlDoc">xml文檔</param>
/// <param name="parentNode">Xml父節(jié)點</param>
/// <param name="name">節(jié)點名</param>
/// <param name="value">節(jié)點值</param>
///
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
//創(chuàng)建對應(yīng)Xml節(jié)點元素
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
#endregionXml數(shù)據(jù)讀取
#region Xml數(shù)據(jù)讀取
/// <summary>
/// 讀取Xml指定節(jié)點中的數(shù)據(jù)
/// </summary>
/// <param name="filePath">Xml文檔路徑</param>
/// <param name="node">節(jié)點</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é)點的節(jié)點數(shù)據(jù)
/// <param name="nodeName">節(jié)點名</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é)點的所有孩子節(jié)點的值
/// <param name="node">要查詢的節(jié)點</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é)點的子節(jié)點
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é)點元素屬性插入數(shù)據(jù)
/// </summary>
/// <param name="path">路徑</param>
/// <param name="node">節(jié)點</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é)點
xmlNode.AppendChild(xe);
//保存Xml文檔
doc.Save(path);
}
catch { }
}
#endregionXml修改數(shù)據(jù)
#region Xml修改數(shù)據(jù)
/// <summary>
/// Xml指定節(jié)點元素屬性修改數(shù)據(jù)
/// </summary>
/// <param name="path">路徑</param>
/// <param name="node">節(jié)點</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é)點</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幫助類
注意:有些方法不能保證百分之百沒有問題的,假如有問題可以留言給我,我會驗證并立即修改。
/// <summary>
/// Xml幫助類
/// </summary>
public class XMLHelper
{
#region Xml反序列化為對象
/// <summary>
/// Xml反序列化為指定模型對象
/// </summary>
/// <typeparam name="T">對象類型</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)容反序列化為指定的對象
/// </summary>
/// <param name="filePath">Xml文件的位置(絕對路徑)</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 對象序列化為Xml
/// 對象序列化為Xml
/// <param name="obj">對象</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();
//強制指定命名空間,覆蓋默認的命名空間
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
//在Xml序列化時去除默認命名空間xmlns:xsd和xmlns:xsi
namespaces.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
//序列化時增加namespaces
serializer.Serialize(sw, obj, namespaces);
sw.Close();
string replaceStr = sw.ToString().Replace(@"<?xml version=""1.0"" encoding=""utf-16""?>", "");
return replaceStr;
#region Xml字符處理
/// 特殊符號轉(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é)點
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//創(chuàng)建Xml根節(jié)點
XmlNode root = xmlDoc.CreateElement("books");
xmlDoc.AppendChild(root);
XmlNode root1 = xmlDoc.CreateElement("book");
root.AppendChild(root1);
//創(chuàng)建子節(jié)點
CreateNode(xmlDoc, root1, "author", "追逐時光者");
CreateNode(xmlDoc, root1, "title", "XML學(xué)習(xí)教程");
CreateNode(xmlDoc, root1, "publisher", "時光出版社");
//將文件保存到指定位置
xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/);
/// <summary>
/// 創(chuàng)建節(jié)點
/// <param name="xmlDoc">xml文檔</param>
/// <param name="parentNode">Xml父節(jié)點</param>
/// <param name="name">節(jié)點名</param>
/// <param name="value">節(jié)點值</param>
///
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
//創(chuàng)建對應(yīng)Xml節(jié)點元素
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
#region Xml數(shù)據(jù)讀取
/// 讀取Xml指定節(jié)點中的數(shù)據(jù)
/// <param name="filePath">Xml文檔路徑</param>
/// <param name="node">節(jié)點</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é)點的節(jié)點數(shù)據(jù)
/// <param name="nodeName">節(jié)點名</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é)點的所有孩子節(jié)點的值
/// <param name="node">要查詢的節(jié)點</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é)點的子節(jié)點
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é)點元素屬性插入數(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é)點
xmlNode.AppendChild(xe);
//保存Xml文檔
doc.Save(path);
#region Xml修改數(shù)據(jù)
/// Xml指定節(jié)點元素屬性修改數(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入分析C#中WinForm控件之Dock順序調(diào)整的詳解
本篇文章是對C#中WinForm控件之Dock順序調(diào)整進行了詳細的分析介紹,需要的朋友參考下2013-05-05
C#ComboBox控件“設(shè)置 DataSource 屬性后無法修改項集合”的解決方法
這篇文章主要介紹了C#ComboBox控件“設(shè)置 DataSource 屬性后無法修改項集合”的解決方法 ,需要的朋友可以參考下2019-04-04
C#實現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法
這篇文章主要介紹了C#實現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法,涉及C#針對json格式數(shù)據(jù)轉(zhuǎn)換的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08

