網(wǎng)站首頁 編程語言 正文
前言
該篇文章主要總結(jié)的是自己平時工作中使用頻率比較高的Xml文檔操作的一些常用方法和收集網(wǎng)上寫的比較好的一些通用Xml文檔操作的方法(主要包括Xml序列化和反序列化,Xml文件讀取,Xml文檔節(jié)點內(nèi)容增刪改的一些通過方法)。當(dāng)然可能還有很多方法會漏了,假如各位同學(xué)好的方法可以在文末留言,我會統(tǒng)一收集起來。
C#XML基礎(chǔ)入門
https://www.jb51.net/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(); //強制指定命名空間,覆蓋默認(rèn)的命名空間 XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); //在Xml序列化時去除默認(rèn)命名空間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; } #endregion
Xml字符處理
#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); #endregion
Xml數(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; #endregion
Xml插入數(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 { } } #endregion
Xml修改數(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 { } } #endregion
Xml刪除數(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(); //強制指定命名空間,覆蓋默認(rèn)的命名空間 XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); //在Xml序列化時去除默認(rèn)命名空間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); }
原文鏈接:https://www.cnblogs.com/Can-daydayup/p/16058817.html
相關(guān)推薦
- 2022-03-16 C#中獲取二維數(shù)組的行數(shù)和列數(shù)以及多維數(shù)組各個維度的長度_C#教程
- 2024-01-15 spring-boot jpa 實現(xiàn)攔截器 StatementInspector
- 2022-07-01 python神經(jīng)網(wǎng)絡(luò)ShuffleNetV2模型復(fù)現(xiàn)詳解_python
- 2023-04-02 GoLang中的timer定時器實現(xiàn)原理分析_Golang
- 2022-12-13 iOS底層實例解析Swift閉包及OC閉包_IOS
- 2022-09-22 判斷數(shù)據(jù)類型的五種方法
- 2022-08-13 Android自定義加載圈的方法_Android
- 2022-09-24 opencv實現(xiàn)圖像校正_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支