c#中xml增删查改
/// <summary>
/// xml转list
/// </summary>
/// <typeparam name="T">目标对象</typeparam>
/// <param name="xmlFullpath">xml文件地址(绝对路径)</param>
/// <param name="nodeName">节点路径(如:nodes/node)</param>
/// <returns></returns>
public static List<T> XmlToList<T>(string xmlFullpath, string nodeName) where T:class
{
List<T> dtos = new List<T>();
XmlDocument doc = new XmlDocument();
if (!File.Exists(xmlFullpath))
{
throw new Exception("未找到数据源:"+xmlFullpath);
}
doc.Load(xmlFullpath);
XmlNodeList nodes = doc.SelectNodes(nodeName);
if (nodes != null && nodes.Count > )
{
foreach (XmlNode node in nodes)
{
var dto = Activator.CreateInstance<T>();
var childNodes = node.ChildNodes;
foreach (XmlNode childNode in childNodes)
{
var property = typeof(T).GetProperty(childNode.Name);
if (property != null)
{
try
{
var value = Convert.ChangeType(childNode.InnerText, property.PropertyType);
property.SetValue(dto, value);
}
catch (Exception ex)
{
throw new Exception(string.Format("字段【{0}】赋值出错,{1}",property.Name,ex.Message));
}
}
}
dtos.Add(dto);
}
}
return dtos;
} /// <summary>
/// 新增xml节点
/// </summary>
/// <typeparam name="T">泛型类</typeparam>
/// <param name="xmlFilePath">xml文件绝对地址</param>
/// <param name="xPath">要添加的xml父级节点路径</param>
/// <param name="nodeName">要添加节点的名称</param>
/// <param name="addList">数据集合</param>
public static void AddXmlNodes<T>(string xmlFilePath, string xPath, string nodeName, List<T> addList) where T : class
{
if (addList == null || addList.Count == )
{
return;
}
if (!File.Exists(xmlFilePath))
{
throw new Exception("文件不存在");
}
var xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
var rootNode = xmlDoc.SelectSingleNode(xPath);
if (rootNode == null)
{
throw new Exception("不存在根节点");
}
foreach (var item in addList)
{
var node = xmlDoc.CreateElement(nodeName);
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
//过滤掉忽略的字段
var ignoreAttr = property.GetCustomAttributes(typeof(IgnoreDataMemberAttribute)).FirstOrDefault();
if (ignoreAttr != null)
continue;
var childNode = xmlDoc.CreateElement(property.Name);
childNode.InnerText = property.GetValue(item) != null ? property.GetValue(item).ToString() : "";
node.AppendChild(childNode);
}
rootNode.AppendChild(node);
}
xmlDoc.Save(xmlFilePath);
} /// <summary>
/// 更新xml节点
/// </summary>
/// <typeparam name="T">泛型类</typeparam>
/// <param name="xmlFilePath">xml文件绝对地址</param>
/// <param name="xPath">要更新的xml父级点路径</param>
/// <param name="key">唯一标识名称</param>
/// <param name="updateList">要更新的数据集</param>
public static void UpdateNodes<T>(string xmlFilePath, string xPath, string key, List<T> updateList) where T : class
{
var xmlDoc = new XmlDocument();
if (!File.Exists(xmlFilePath))
{
throw new Exception("文件不存在");
}
xmlDoc.Load(xmlFilePath);
var rootNode = xmlDoc.SelectSingleNode(xPath);
if (rootNode == null)
{
throw new Exception("xml节点不存在");
}
var nodes = rootNode.ChildNodes;
foreach (var item in updateList)
{
var properties = typeof(T).GetProperties();
var keyItem = properties.FirstOrDefault(t => t.Name == key);
if (keyItem == null)
throw new Exception("未在泛型类中查找到与唯一标识名称对应的字段属性");
var keyValue = keyItem.GetValue(item, null);
if (keyValue==null)
{
throw new Exception(string.Format("唯一标识{0}值不能为空",key));
}
foreach (XmlNode node in nodes)
{
var xmlKeyNode = node.SelectSingleNode(key);
if (xmlKeyNode != null && xmlKeyNode.InnerText == keyValue.ToString())
{
foreach (XmlNode child in node.ChildNodes)
{
var childItem = properties.FirstOrDefault(t => t.Name == child.Name);
if (childItem != null)
{
child.InnerText = childItem.GetValue(item).ToString();
}
}
break;
}
}
}
xmlDoc.Save(xmlFilePath);
} /// <summary>
/// 删除xml节点
/// </summary>
/// <typeparam name="T">泛型类</typeparam>
/// <param name="xmlFilePath">xml文件绝对地址</param>
/// <param name="xPath">要删除的xml父级点路径</param>
/// <param name="key">唯一标识名称</param>
/// <param name="deleteList">要删除的数据集</param>
public static void DeleteNodes<T>(string xmlFilePath, string xPath, string key, List<T> deleteList) where T : class
{
var xmlDoc = new XmlDocument();
if (!File.Exists(xmlFilePath))
{
throw new Exception("文件不存在");
}
xmlDoc.Load(xmlFilePath);
var rootNode = xmlDoc.SelectSingleNode(xPath);
if (rootNode == null)
{
throw new Exception("xml节点不存在");
}
var nodes = rootNode.ChildNodes;
foreach (var item in deleteList)
{
var properties = typeof(T).GetProperties();
var keyItem = properties.FirstOrDefault(t => t.Name == key);
if (keyItem == null)
throw new Exception("未在泛型类中查找到与唯一标识名称对应的字段属性");
var keyValue = keyItem.GetValue(item, null);
if (keyValue == null)
{
throw new Exception(string.Format("唯一标识{0}值不能为空", key));
}
foreach (XmlNode node in nodes)
{
var xmlKeyNode = node.SelectSingleNode(key);
if (xmlKeyNode != null && xmlKeyNode.InnerText == keyValue.ToString())
{
rootNode.RemoveChild(node);
break;
}
}
}
xmlDoc.Save(xmlFilePath);
}
c#中xml增删查改的更多相关文章
- java中CRUD(增删查改)底层代码的实现
java中CRUD(增删查改)底层代码的实现: package com.station.dao; import com.station.model.Product; import java.sql.* ...
- js中数组增删查改unshift、push、pop、shift、slice、indexOf、concat、join
js中数组增删查改unshift.push.pop.shift.slice.indexOf.concat.join
- MongoDB 学习笔记(二):shell中执行增删查改
一.查 1.查询集合中所有文档:db.集合名.find(). 2.查询集合中第一个文档:db.集合名.findOne(). 3.指定查询条件:第一个参数就是指定查询条件 查询全部文档:db.集合名.f ...
- C# xml增删查改
C# XML XmlDocument 添加命名空间: using System.Xml; 定义公共对象: XmlDocument xmldoc ; XmlNode xmlnode ; XmlEleme ...
- linq to xml 增删查改
一.XML基本概述 XML文件是一种常用的文件格式,例如WinForm里面的app.config以及Web程序中的web.config文件,还有许多重要的场所都有它的身影.Xml是Internet环境 ...
- XML 增删查改
<?xml version="1.0" encoding="utf-8"?> <users> <person name=" ...
- Ubuntu 中 iptables 增删查改
iptables是linux系统自带的防火墙,功能强大.如果iptables不熟悉的话可以用apf,是一款基于iptables的防墙. 一.安装并启动防火墙 $ /etc/init.d/iptable ...
- jdbc的实例应用:增删查改实现
//在jdbc中进行增删查改 //查看所有 public static void findAll() { String url = "jdbc:mysql://localhost:3306/ ...
- Android SQLite最简单demo实现(增删查改)
本来不太想写这篇博客的,但是看到网上的关于android数据库操作的博文都讲得很详细,对于像我这样的新手入门了解SQLite的基本操作有一定难度,所以我参考了网上的一些博客文章,并自己亲自摸索了一遍, ...
随机推荐
- [译]Vulkan教程(07)物理设备和队列家族
[译]Vulkan教程(07)物理设备和队列家族 Selecting a physical device 选择一个物理设备 After initializing the Vulkan library ...
- Laravel-权限系统
总结Auth中间件用于定义未登录用户只能操作哪些权限policy授权策略定义了当前用户实例与进行授权的用户是否匹配,一致才能进一步操作,否则返回403禁止访问异常场景:用户登录 Auth步骤 找到需要 ...
- idea中导入别人的vue项目并运行
1. 下载node.js 在搭建vue的开发环境之前,先下载node.js,下载地址:https://nodejs.org/en/ https://blog.csdn.net/antma/articl ...
- 为什么老外不愿意用MyBatis?
作者:陈龙 www.zhihu.com/question/309662829 Spring 团队的Josh Long自己在Twitter上做了一个调查.1625次投票,样本量不算大,但也能说明问题.和 ...
- Vue-element-admin实现菜单根据用户权限动态加载
之前有一些网友对我那个IT部门信息管理系统(http://caijt.com/it)的前端感兴趣,我已经开源到github(https://github.com/Caijt/itsys-ui) 上面有 ...
- javaWeb核心技术第十一篇之Listener
监听器:所谓的监听器是指对整个WEB环境的监听,当被监视的对象发生改变时,立即调用相应的方法进行处理. 监听术语: 事件源:被监听的对象. 监听器对象:监听事件源的对象 注册或绑定:1和2结合的过程 ...
- Ubuntu Server中怎样卸载keepalived
场景 在Ubuntu Server中进行安装keepalived ,如果安装过程中出现纰漏,想要重新安装keepalived或者就是想直接卸载keepalived. 我们在安装keepalived时指 ...
- 关于async function(){ let res = await } 详解
本文引自: https://www.jianshu.com/p/435a8b8cc7d3 async function fn(){ //表示异步,这个函数里面有异步任务 let result = aw ...
- ABP入门教程5 - 界面调整
点这里进入ABP入门教程目录 调整前 调整后 调整项 页面标题 把favicon.ico替换为指定Logo JD.CRS.Web.Mvc\wwwroot\favicon.ico 顶部工具栏 把logo ...
- Thread <number> cannot allocate new log, sequence <number>浅析
有时候,你会在ORACLE数据库的告警日志中发现"Thread <number> cannot allocate new log, sequence <number> ...