[C#]XML操作类

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;
using System.IO;
using System.Reflection;

namespace FrmUpdate
{
    public class XmlHelper
    {
        /// <summary>--检查XML文件是否存在,不存在则先创建--
        /// Guo Jin
        /// </summary>
        /// <param name="baseDirectory">文件完整目录</param>
        /// <param name="fileName">文件名称</param>
        /// <returns>真/假</returns>
        private static bool CheckXmlFilesIsExists(string baseDirectory, string fileName)
        {
            bool isOk = true;
            DirectoryInfo dir = null;
            if (!Directory.Exists(baseDirectory))
            {
                try
                {
                    dir = new DirectoryInfo(baseDirectory);
                    dir.Create();
                }
                catch (IOException ex)
                {
                    isOk = false;
                    throw new Exception("创建"   baseDirectory   "失败:"   ex.Message);
                }
            }

            string filePath = baseDirectory   "\\"   fileName   ".ini";
            if (!File.Exists(filePath))
            {
                try
                {
                    FileStream fs = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    string xmlHead = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>"   Environment.NewLine   "<Items></Items>";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlHead);
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Flush();
                    fs.Close();
                    isOk = true;
                }
                catch (IOException ex)
                {
                    isOk = false;
                    throw new Exception("创建"   fileName   "失败:"   ex.Message);
                }
            }
            return isOk;
        }

        /// <summary>--把业务数据保存为xml数据存储在本机--
        /// Guo Jin 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="baseDir">程序启动路径</param>
        /// <param name="baseDir">文件名称</param>
        /// <param name="model">业务实体</param>
        /// <returns>真\假</returns>
        public static bool SaveAsXml<T>(string baseDir, string fileName, List<T> models)
        {
            bool result = false;
            XmlDocument doc = null;
            try
            {
                if (!CheckXmlFilesIsExists(baseDir, fileName))
                {
                    return false;
                }
                doc = new XmlDocument();
                doc.Load(baseDir   @"\"   fileName   ".ini");

                XmlNode root = doc.SelectSingleNode(@"//Items");//获取根节点
                XmlElement element;//元素
                XmlAttribute temp;//属性
                PropertyInfo[] propinfos = null;
                foreach (T obj in models)
                {
                    if (models != null)
                    {
                        Type ty = obj.GetType();
                        propinfos = ty.GetProperties();//循环获取每个实体里面的所有属性。
                    }

                    element = doc.CreateElement(fileName);//为每个实体创建一个xml元素

                    foreach (PropertyInfo attb in propinfos)
                    {
                        temp = doc.CreateAttribute(attb.Name);
                        temp.Value = attb.GetValue(obj, null) == null ? "" : attb.GetValue(obj, null).ToString();
                        element.Attributes.Append(temp);
                    }
                    root.AppendChild(element);

                }

                doc.Save(baseDir   @"\"   fileName   ".ini");
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                throw ex;
            }
            return result;
        }

        /// <summary>--根据条件到对应的Xml文件中检索数据
        /// Guo Jin
        /// </summary>
        /// <param name="baseDirectory">文件完整目录</param>
        /// <param name="fileName">Xml文件名</param>
        /// <param name="condition">条件</param>
        /// <param name="conditionValue">条件值</param>
        /// <returns>XmlNodeList</returns>
        public static XmlNodeList GetDataFromXml(string baseDirectory, string fileName, string condition, string conditionValue)
        {
            XmlNodeList list = null;
            XmlDocument doc = null;
            try
            {
                string pathTemp = "";
                if (!string.IsNullOrEmpty(baseDirectory))
                {
                    pathTemp = baseDirectory   "\\"   fileName   ".ini";
                }

                if (File.Exists(pathTemp))
                {
                    doc = new XmlDocument();
                    doc.Load(pathTemp);

                    string[] conditions = condition.Split(',');
                    string[] conditionValues = conditionValue.Split(',');
                    StringBuilder sb = new StringBuilder();
                    sb.Append(@"/Items/"   fileName   "[");

                    for (int i = 0; i < conditions.Length; i  )
                    {
                        if (conditions.Length == 1)//如果就一个条件
                        {
                            sb.Append("@"   conditions[i]   "'"   conditionValues[i]   "' ");
                        }
                        else if (conditions.Length > 1 && i != (conditions.Length - 1))//如果是多个条件,并且不是最后一个
                        {
                            sb.Append("@"   conditions[i]   "'"   conditionValues[i]   "' and ");
                        }
                        else if (conditions.Length != 1 && i == (conditions.Length - 1))
                        {
                            sb.Append("@"   conditions[i]   "'"   conditionValues[i]   "' ");
                        }
                    }

                    sb.Append("]");

                    list = doc.SelectNodes(sb.ToString());
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return list;
        }

        /// <summary>--从xml文件中获取数据--
        /// Guo Jin
        /// </summary>
        /// <param name="baseDirectory">文件完整目录</param>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        public static XmlNodeList GetDataFromXml(string baseDirectory, string fileName)
        {
            XmlNodeList list = null;
            XmlDocument doc = null;
            try
            {
                string pathTemp = "";
                if (!string.IsNullOrEmpty(baseDirectory))
                {
                    pathTemp = baseDirectory   "\\"   fileName   ".ini";
                }
                if (File.Exists(pathTemp))
                {
                    doc = new XmlDocument();
                    doc.Load(pathTemp);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(@"/Items/"   fileName);
                    list = doc.SelectNodes(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return list;
        }

        /// <summary>--保存Xml文件--
        /// Guo Jin
        /// </summary>
        /// <param name="baseDir">完整路径</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="tab">要写入的Hashtable</param>
        /// <returns>真/假</returns>
        public static bool SaveAsXml(string baseDir, string fileName, Hashtable tab)
        {
            bool result = false;
            XmlDocument doc = null;
            try
            {
                if (!CheckXmlFilesIsExists(baseDir, fileName))
                {
                    return false;
                }
                doc = new XmlDocument();
                doc.Load(baseDir   @"\"   fileName   ".ini");

                XmlNode root = doc.SelectSingleNode(@"//Items");//获取根节点
                XmlElement element;//元素

                foreach (DictionaryEntry de in tab)
                {
                    XmlNode node = doc.SelectSingleNode(@"//Items//"   de.Key.ToString());
                    if (node == null)
                    {
                        //添加元素
                        element = doc.CreateElement(de.Key.ToString());
                        element.InnerText = de.Value.ToString();

                        root.AppendChild(element);
                    }
                    else
                    {
                        //修改元素值
                        node.InnerText = de.Value.ToString();
                    }
                }
                doc.Save(baseDir   @"\"   fileName   ".ini");
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                throw ex;
            }
            return result;
        }

        /// <summary>--更新XML中某个元素的属性值--
        /// Guo Jin
        /// </summary>
        /// <param name="filePath">xml文件的完整路径</param>
        /// <param name="fileName">xml文件的名称,除去后缀名</param>
        /// <param name="where">检索条件</param>
        /// <param name="dis">要设置的元素的属性</param>
        /// <param name="val">更新的值</param>
        /// <returns>真/假</returns>
        public static bool UpdateXml(string filePath, string fileName, string where, string dis, string val)
        {
            bool result = false;
            XmlDocument doc = null;
            try
            {
                if (File.Exists(filePath))
                {
                    doc = new XmlDocument();
                    doc.Load(filePath);

                    XmlNode node = doc.SelectSingleNode(@"//Items//"   fileName   "[@"   where   "]");
                    if (node != null)
                    {
                        node.Attributes[dis].Value = val;
                        doc.Save(filePath);
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
                throw ex;
            }
            return result;
        }

        /// <summary>--根据某元素的文本--
        /// Guo Jin
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="nodeName">元素名称</param>
        /// <returns>该元素的Text</returns>
        public static string GetXmlNodeText(string path, string nodeName)
        {
            XmlDocument doc = null;
            try
            {
                doc = new XmlDocument();
                doc.Load(path);
                StringBuilder sb = new StringBuilder();
                sb.Append(@"/Items/"   nodeName);
                XmlNode node = doc.SelectSingleNode(sb.ToString());
                if (node != null)
                {
                    return node.InnerText;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return "";
        }
    }
}
posted @ 2012-07-18 16:25  Hsppl  阅读(234)  评论(0编辑  收藏  举报