XmlHelper 通用类

    /// <summary>
    /// 提供对XML数据的读写
    /// </summary>
    public sealed class XmlHelper
    {
        /// <summary>
        /// 声明一个XmlDocument空对象
        /// </summary>
        private XmlDocument _xmlDoc = new XmlDocument();
        /// <summary>
        /// 构造函数,导入Xml文件
        /// </summary>
        /// <param name="xmlFile">文件绝对路径</param>
        public XmlHelper(string xmlFile)
        {
            try
            {
                _xmlDoc.Load(xmlFile);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        ~XmlHelper()
        {
            _xmlDoc = null; // 释放XmlDocument对象
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="filePath">文件绝对路径</param>
        public void Save(string filePath)
        {
            try
            {
                _xmlDoc.Save(filePath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 根据Xml文件的节点路径,返回一个DataSet数据集
        /// </summary>
        /// <param name="xmlPathNode">Xml文件的某个节点</param>
        /// <returns></returns>
        public DataSet GetDataSet(string xmlPathNode)
        {
            DataSet ds = new DataSet();
            try
            {
                System.IO.StringReader read = new System.IO.StringReader(_xmlDoc.SelectSingleNode(xmlPathNode).OuterXml);
                ds.ReadXml(read);
                read.Close();
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return ds;
        }
        /// <summary>
        /// 属性查询,返回属性值
        /// </summary>
        /// <param name="xmlPathNode">属性所在的节点</param>
        /// <param name="attributeName">属性名</param>
        /// <returns></returns>
        public string GetAttributeValue(string xmlPathNode, string attributeName)
        {
            string rlt = string.Empty;
            try
            {
                rlt = _xmlDoc.SelectSingleNode(xmlPathNode).Attributes[attributeName].Value;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return rlt;
        }
        /// <summary>
        /// 节点查询,返回节点值
        /// </summary>
        /// <param name="xmlPathNode">节点的路径</param>
        /// <returns></returns>
        public string GetNodeText(string xmlPathNode)
        {
            string txt = _xmlDoc.SelectSingleNode(xmlPathNode).InnerText;
            if (null == txt || string.Empty == txt)
            {
                return string.Empty;
            }
            return txt;
        }
        /// <summary>
        /// 节点值查询判断
        /// </summary>
        /// <param name="xmlPathNode">父节点</param>
        /// <param name="index">节点索引</param>
        /// <param name="nodeText">节点值</param>
        /// <returns></returns>
        public bool IsValidNode(string xmlPathNode, int index, string nodeText)
        {
            try
            {
                XmlNodeList nodeList = _xmlDoc.SelectNodes(xmlPathNode);
                // 循环遍历节点,查询是否存在该节点
                for (int i = 0; i < nodeList.Count; i++)
                {
                    if (nodeText == nodeList[i].ChildNodes[index].InnerText)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return false;
        }
        /// <summary>
        /// 获取子节点个数
        /// </summary>
        /// <param name="xmlPathNode">父节点</param>
        /// <returns></returns>
        public int NodeCount(string xmlPathNode)
        {
            int rlt = 0;
            try
            {
                rlt = _xmlDoc.SelectSingleNode(xmlPathNode).ChildNodes.Count;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                rlt = 0;
            }
            return rlt;
        }
        /// <summary>
        /// 更新一个节点的内容
        /// </summary>
        /// <param name="xmlPathNode">节点的路径</param>
        /// <param name="nodeContent">新的节点值</param>
        /// <returns></returns>
        public bool UpdateNode(string xmlPathNode, string nodeContent)
        {
            try
            {
                _xmlDoc.SelectSingleNode(xmlPathNode).InnerText = nodeContent;
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 更新N个节点值
        /// </summary>
        /// <param name="xmlParentNode">父节点</param>
        /// <param name="xmlNodes">子节点</param>
        /// <param name="nodeContents">子节点内容</param>
        /// <returns></returns>
        public bool UpdateNode(string xmlParentNode, string[] xmlNodes, string[] nodeContents)
        {
            try
            {
                // 根据节点数组循环修改节点值
                for (int i = 0; i < xmlNodes.Length; i++)
                {
                    _xmlDoc.SelectSingleNode(xmlParentNode + "/" + xmlNodes[i]).InnerText = nodeContents[i];
                }
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 修改属性
        /// </summary>
        /// <param name="xmlPathNode">属性所在的节点</param>
        /// <param name="attributeName">属性名</param>
        /// <param name="attributeValue">属性值</param>
        /// <returns></returns>
        public bool UpdateAttributeValue(string xmlPathNode, string attributeName, string attributeValue)
        {
            try
            {
                _xmlDoc.SelectSingleNode(xmlPathNode).Attributes[attributeName].Value = attributeValue;
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 添加属性
        /// </summary>
        /// <param name="xmlPathNode">属性所在的节点</param>
        /// <param name="attributeName">属性名</param>
        /// <param name="attributeValue">属性值</param>
        /// <returns></returns>
        public bool InsertAttribute(string xmlPathNode, string attributeName, string attributeValue)
        {
            try
            {
                XmlElement element = (XmlElement)_xmlDoc.SelectSingleNode(xmlPathNode);
                element.SetAttribute(attributeName, attributeValue);
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 插入一个节点,带N个子节点
        /// </summary>
        /// <param name="xmlPathNode">当前节点</param>
        /// <param name="nodeName">插入节点的名称</param>
        /// <param name="elementNames">子节点的名称数组</param>
        /// <param name="contents">子节点的内容数组</param>
        /// <returns></returns>
        public bool InsertNode(string xmlPathNode, string nodeName, string[] elementNames, string[] contents)
        {
            try
            {
                XmlNode node = _xmlDoc.SelectSingleNode(xmlPathNode);
                XmlElement childNode = _xmlDoc.CreateElement(nodeName);
                node.AppendChild(childNode);
                for (int i = 0; i < elementNames.Length; i++)
                {
                    XmlElement element = _xmlDoc.CreateElement(elementNames[i]);
                    element.InnerText = contents[i];
                    childNode.AppendChild(element);
                }
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 删除一个节点
        /// </summary>
        /// <param name="xmlPathNode">节点的路径</param>
        /// <returns></returns>
        public bool DeleteNode(string xmlPathNode)
        {
            try
            {
                _xmlDoc.SelectSingleNode(xmlPathNode).ParentNode.RemoveChild(_xmlDoc.SelectSingleNode(xmlPathNode));
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 将对象序列化成XML
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="hasNamespace">是否有Xml头部</param>
        /// <returns></returns>
        public static string Serialize(object obj, bool hasNamespace = false)
        {
            string xml = string.Empty;
            try
            {
                var sb = new StringBuilder();
                var xmlSettings = new XmlWriterSettings();
                xmlSettings.OmitXmlDeclaration = hasNamespace;
                // 换行缩进
                xmlSettings.Indent = true;
                xmlSettings.Encoding = System.Text.Encoding.Default;
                using (var xmlWriter = XmlWriter.Create(sb, xmlSettings))
                {
                    var xmlSerializer = new XmlSerializer(obj.GetType());
                    // 去除默认命名空间xmlns:xsd和xmlns:xsi
                    var xmlNampespace = new XmlSerializerNamespaces();
                    xmlNampespace.Add("", "");

                    if (hasNamespace)
                    {
                        xmlSerializer.Serialize(xmlWriter, obj);
                    }
                    else
                    {
                        xmlSerializer.Serialize(xmlWriter, obj, xmlNampespace);
                    }
                    xml = sb.ToString();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return xml;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="xmlStr">xml字符串</param>
        /// <returns>反序列化模型</returns>
        public static T DeSerialize<T>(string xmlStr)
        {
            return (T)Deserialize(typeof(T), xmlStr);
        }
        private static object Deserialize(Type type, string xmlStr)
        {
            try
            {
                using (var sr = new StringReader(xmlStr))
                {
                    var serializer = new XmlSerializer(type);
                    return serializer.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 将XML文本写入指定文件
        /// </summary>
        /// <param name="filePath">绝对路径</param>
        /// <param name="xmlStr">XML文本</param>
        /// <returns></returns>
        public static bool WriteXmlString(string filePath, string xmlStr)
        {
            try
            {
                File.WriteAllText(filePath, xmlStr);
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 读取XML文本
        /// </summary>
        /// <param name="filePath">绝对路径</param>
        /// <returns></returns>
        public static string ReadXmlString(string filePath)
        {
            try
            {
                return File.ReadAllText(filePath, Encoding.Default);
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

    }

Demo

原文地址:https://www.cnblogs.com/wesson2019-blog/p/12127433.html

时间: 2024-10-11 16:35:49

XmlHelper 通用类的相关文章

[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口IXmlSerializable实现XML序列化及XML通用类

[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口IXmlSerializable实现XML序列化及XML通用类 本节导读:本节主要介绍通过序列化接口IXmlSerializable实现XML序列化和反序列化,整理了XML基础操作及序列化的通用类(包括XML及节点的基础读写操作,XML到DataSet\DataTable互转换操作,XML序列化及反序列化通用方法等). 读前必备: A.类和类的实例 [.net 面向对象编程基础]  (9) 类和类的

C#---数据库访问通用类、Access数据库操作类、mysql类 .[转]

原文链接 //C# 数据库访问通用类 (ADO.NET)using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient;using System.Configuration; namespace XXX{    /// <summary>    /// 针对SQL Server数据库操作的通用类           /// </sum

jQuery Ajax封装通用类 (linjq)

jQuery Ajax封装通用类 (linjq) $(function(){ /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * async 默认值: true.默认设置下,所有请求均为异步请求.如果需要发送同步请求,请将此选项设置为 false. * 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行. * t

poi导出excel通用类

一.关键的通用类public class PoiExportUtils {    private static HSSFWorkbook workBook; public PoiExportUtils(){        workBook = new HSSFWorkbook();    }        /**     * 创建sheet     * @param sheetName     * @param workBook     * @return     */    public st

PHP curl get post通用类

<?php /** * @author:xiaojiang * curl 通用方法 ..get /post 传送数据 */ class process{ const GET = 0; const POST = 1; public $url; public $ch = null; private $type = 1; public function __construct( $url , $type = self::POST){ $this->url = $url; $this->ch =

DataTable转换为List&lt;Model&gt;的通用类

在开发中,把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便. 所以很多人都是按照以下方式做的: // 获得查询结果DataTable dt = DbHelper.ExecuteDataTable(...);// 把DataTable转换为IList<UserInfo>IList<UserInfo> users = ConvertToUserInfo(dt); 问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为

MVC AJAX导出Excel通用类

通用类: public enum DataTypeEnum { Int = 0, Float = 1, Double = 2, String = 3, DateTime = 4, Date = 5 } public class ExportFieldInfo { /// <summary> /// 字段名,用于反射获取值 /// </summary> public string FieldName { get; set; } /// <summary> /// 中文名,

Memcached通用类(基于enyim.com Memcached Client)

一.如果用官方提供的方法,在web.config里面配置好了各个参数和服务器IP.如下图: <?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="enyim.com"> <section name="memcached" type="Enyim.Caching.Configuration.

ASP.NET文件操作通用类

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.IO; 7 using System.Web; 8 using System.Web.UI; 9 using System.Web.UI.WebControls; 10 11 12 public class WebFileHelper 13 { 14 15 FileInfo f