博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[C#]XML操作类
阅读量:7015 次
发布时间:2019-06-28

本文共 10150 字,大约阅读时间需要 33 分钟。

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    {        /// --检查XML文件是否存在,不存在则先创建--        /// Guo Jin        ///         /// 文件完整目录        /// 文件名称        /// 
真/假
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 = "
" Environment.NewLine "
"; 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; } /// --把业务数据保存为xml数据存储在本机-- /// Guo Jin /// ///
/// 程序启动路径 /// 文件名称 /// 业务实体 ///
真\假
public static bool SaveAsXml
(string baseDir, string fileName, List
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; } ///
--根据条件到对应的Xml文件中检索数据 /// Guo Jin /// ///
文件完整目录 ///
Xml文件名 ///
条件 ///
条件值 ///
XmlNodeList
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; } ///
--从xml文件中获取数据-- /// Guo Jin /// ///
文件完整目录 ///
文件名称 ///
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; } ///
--保存Xml文件-- /// Guo Jin /// ///
完整路径 ///
文件名称 ///
要写入的Hashtable ///
真/假
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; } ///
--更新XML中某个元素的属性值-- /// Guo Jin /// ///
xml文件的完整路径 ///
xml文件的名称,除去后缀名 ///
检索条件 ///
要设置的元素的属性 ///
更新的值 ///
真/假
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; } ///
--根据某元素的文本-- /// Guo Jin /// ///
文件路径 ///
元素名称 ///
该元素的Text
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 ""; } }}

转载于:https://www.cnblogs.com/Hsppl/archive/2012/07/18/2597650.html

你可能感兴趣的文章
深入学习Hive应用场景及架构原理
查看>>
HDU_1143_tri tiling
查看>>
codeforces_1075_C. The Tower is Going Home
查看>>
C# 关于XML的简单操作实例
查看>>
ggplot2:画世界地图和中国地图 合并数据 增添信息 标记
查看>>
VertexBuffer渲染次序
查看>>
python中使用 xpath
查看>>
集中管理:领导者,不能不考虑的几件事之—— 拿什么辅助你,我的决策?(一)...
查看>>
关于VirtualBox虚拟机安装GhostXP出现蓝屏proce***.sys 的解决办法
查看>>
JSP如何在servlet将一个数据模型对象传递给jsp页面
查看>>
PHP 实现“贴吧神兽”验证码
查看>>
根据一个表的数据情况显示另一个表的数据
查看>>
TP4056大电流1A使用注意事项
查看>>
Java常考面试题(四)
查看>>
学习Javascript闭包(Closure)
查看>>
你性格那么软,总是经常改变想法
查看>>
NeHe OpenGL教程 第十七课:2D图像文字
查看>>
学习SpringMVC——从HelloWorld开始
查看>>
awk打印指定列以后的所有内容
查看>>
代码16
查看>>