网站首页 编程语言 正文
目录
- 前言
- C#XML基础入门
- 对象序列化为Xml
- Xml字符处理
- 创建Xml文档
- Xml数据读取
- Xml插入数据
- Xml修改数据
- Xml删除数据
- 完整的XmlHelper帮助类
前言
该篇文章主要总结的是自己平时工作中使用频率比较高的Xml文档操作的一些常用方法和收集网上写的比较好的一些通用Xml文档操作的方法(主要包括Xml序列化和反序列化,Xml文件读取,Xml文档节点内容增删改的一些通过方法)。当然可能还有很多方法会漏了,假如各位同学好的方法可以在文末留言,我会统一收集起来。
C#XML基础入门
https://www.jb51.net/article/104113.htm
Xml反序列化为对象
#region Xml反序列化为对象 /// <summary> /// Xml反序列化为指定模型对象 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="xmlContent">Xml内容</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文件内容反序列化为指定的对象 /// </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; } #endregion
Xml字符处理
#region Xml字符处理 /// <summary> /// 特殊符号转换为转义字符 /// </summary> /// <param name="xmlStr"></param> /// <returns></returns> public string XmlSpecialSymbolConvert(string xmlStr) { return xmlStr.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\'", "'").Replace("\"", """); } #endregion
创建Xml文档
#region 创建Xml文档 /// <summary> /// 创建Xml文档 /// </summary> /// <param name="saveFilePath">文件保存位置</param> public void CreateXmlDocument(string saveFilePath) { XmlDocument xmlDoc = new XmlDocument(); //创建类型声明节点 XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", ""); xmlDoc.AppendChild(node); //创建Xml根节点 XmlNode root = xmlDoc.CreateElement("books"); xmlDoc.AppendChild(root); XmlNode root1 = xmlDoc.CreateElement("book"); root.AppendChild(root1); //创建子节点 CreateNode(xmlDoc, root1, "author", "追逐时光者"); CreateNode(xmlDoc, root1, "title", "XML学习教程"); CreateNode(xmlDoc, root1, "publisher", "时光出版社"); //将文件保存到指定位置 xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/); } /// <summary> /// 创建节点 /// </summary> /// <param name="xmlDoc">xml文档</param> /// <param name="parentNode">Xml父节点</param> /// <param name="name">节点名</param> /// <param name="value">节点值</param> /// public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value) //创建对应Xml节点元素 XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null); node.InnerText = value; parentNode.AppendChild(node); #endregion
Xml数据读取
#region Xml数据读取 /// <summary> /// 读取Xml指定节点中的数据 /// </summary> /// <param name="filePath">Xml文档路径</param> /// <param name="node">节点</param> /// <param name="attribute">读取数据的属性名</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文件中指定节点的节点数据 /// <param name="nodeName">节点名</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("//" + nodeName); if (node != null) XmlString = node.InnerText; return XmlString; /// 获取某一节点的所有孩子节点的值 /// <param name="node">要查询的节点</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; //得到该节点的子节点 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插入数据
#region Xml插入数据 /// <summary> /// Xml指定节点元素属性插入数据 /// </summary> /// <param name="path">路径</param> /// <param name="node">节点</param> /// <param name="element">元素名</param> /// <param name="attribute">属性名</param> /// <param name="value">属性数据</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 //添加新增的节点 xmlNode.AppendChild(xe); //保存Xml文档 doc.Save(path); } catch { } } #endregion
Xml修改数据
#region Xml修改数据 /// <summary> /// Xml指定节点元素属性修改数据 /// </summary> /// <param name="path">路径</param> /// <param name="node">节点</param> /// <param name="attribute">属性名</param> /// <param name="value">属性数据</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删除数据
#region Xml删除数据 /// <summary> /// 删除数据 /// </summary> /// <param name="path">路径</param> /// <param name="node">节点</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内容</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文件内容反序列化为指定的对象 /// </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字符处理 /// 特殊符号转换为转义字符 /// <param name="xmlStr"></param> public string XmlSpecialSymbolConvert(string xmlStr) return xmlStr.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\'", "'").Replace("\"", """); #region 创建Xml文档 /// 创建Xml文档 /// <param name="saveFilePath">文件保存位置</param> public void CreateXmlDocument(string saveFilePath) XmlDocument xmlDoc = new XmlDocument(); //创建类型声明节点 XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", ""); xmlDoc.AppendChild(node); //创建Xml根节点 XmlNode root = xmlDoc.CreateElement("books"); xmlDoc.AppendChild(root); XmlNode root1 = xmlDoc.CreateElement("book"); root.AppendChild(root1); //创建子节点 CreateNode(xmlDoc, root1, "author", "追逐时光者"); CreateNode(xmlDoc, root1, "title", "XML学习教程"); CreateNode(xmlDoc, root1, "publisher", "时光出版社"); //将文件保存到指定位置 xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/); /// <summary> /// 创建节点 /// <param name="xmlDoc">xml文档</param> /// <param name="parentNode">Xml父节点</param> /// <param name="name">节点名</param> /// <param name="value">节点值</param> /// public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value) //创建对应Xml节点元素 XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null); node.InnerText = value; parentNode.AppendChild(node); #region Xml数据读取 /// 读取Xml指定节点中的数据 /// <param name="filePath">Xml文档路径</param> /// <param name="node">节点</param> /// <param name="attribute">读取数据的属性名</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文件中指定节点的节点数据 /// <param name="nodeName">节点名</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("//" + nodeName); if (node != null) XmlString = node.InnerText; return XmlString; /// 获取某一节点的所有孩子节点的值 /// <param name="node">要查询的节点</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; //得到该节点的子节点 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插入数据 /// Xml指定节点元素属性插入数据 /// <param name="path">路径</param> /// <param name="element">元素名</param> /// <param name="attribute">属性名</param> /// <param name="value">属性数据</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 //添加新增的节点 xmlNode.AppendChild(xe); //保存Xml文档 doc.Save(path); #region Xml修改数据 /// Xml指定节点元素属性修改数据 * 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删除数据 /// 删除数据 * 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
相关推荐
- 2022-01-03 比较throw和 throws的异同
- 2022-05-21 python实现会员管理系统_python
- 2022-12-28 React+Electron快速创建并打包成桌面应用的实例代码_React
- 2022-06-06 浅谈Redis 中的过期删除策略和内存淘汰机制_Redis
- 2022-08-14 Android实现显示和隐藏密码功能的示例代码_Android
- 2022-05-06 C语言中回调函数的使用详情_C 语言
- 2022-07-28 C++中strlen(),sizeof()与size()的区别_C 语言
- 2023-05-07 Go项目配置管理神器之viper的介绍与使用详解_Golang
- 最近更新
-
- window11 系统安装 yarn
- 超详细win安装深度学习环境2025年最新版(
- Linux 中运行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存储小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基础操作-- 运算符,流程控制 Flo
- 1. Int 和Integer 的区别,Jav
- spring @retryable不生效的一种
- Spring Security之认证信息的处理
- Spring Security之认证过滤器
- Spring Security概述快速入门
- Spring Security之配置体系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置权
- redisson分布式锁中waittime的设
- maven:解决release错误:Artif
- restTemplate使用总结
- Spring Security之安全异常处理
- MybatisPlus优雅实现加密?
- Spring ioc容器与Bean的生命周期。
- 【探索SpringCloud】服务发现-Nac
- Spring Security之基于HttpR
- Redis 底层数据结构-简单动态字符串(SD
- arthas操作spring被代理目标对象命令
- Spring中的单例模式应用详解
- 聊聊消息队列,发送消息的4种方式
- bootspring第三方资源配置管理
- GIT同步修改后的远程分支