/// <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增删查改的更多相关文章

  1. java中CRUD(增删查改)底层代码的实现

    java中CRUD(增删查改)底层代码的实现: package com.station.dao; import com.station.model.Product; import java.sql.* ...

  2. js中数组增删查改unshift、push、pop、shift、slice、indexOf、concat、join

    js中数组增删查改unshift.push.pop.shift.slice.indexOf.concat.join

  3. MongoDB 学习笔记(二):shell中执行增删查改

    一.查 1.查询集合中所有文档:db.集合名.find(). 2.查询集合中第一个文档:db.集合名.findOne(). 3.指定查询条件:第一个参数就是指定查询条件 查询全部文档:db.集合名.f ...

  4. C# xml增删查改

    C# XML XmlDocument 添加命名空间: using System.Xml; 定义公共对象: XmlDocument xmldoc ; XmlNode xmlnode ; XmlEleme ...

  5. linq to xml 增删查改

    一.XML基本概述 XML文件是一种常用的文件格式,例如WinForm里面的app.config以及Web程序中的web.config文件,还有许多重要的场所都有它的身影.Xml是Internet环境 ...

  6. XML 增删查改

    <?xml version="1.0" encoding="utf-8"?> <users> <person name=" ...

  7. Ubuntu 中 iptables 增删查改

    iptables是linux系统自带的防火墙,功能强大.如果iptables不熟悉的话可以用apf,是一款基于iptables的防墙. 一.安装并启动防火墙 $ /etc/init.d/iptable ...

  8. jdbc的实例应用:增删查改实现

    //在jdbc中进行增删查改 //查看所有 public static void findAll() { String url = "jdbc:mysql://localhost:3306/ ...

  9. Android SQLite最简单demo实现(增删查改)

    本来不太想写这篇博客的,但是看到网上的关于android数据库操作的博文都讲得很详细,对于像我这样的新手入门了解SQLite的基本操作有一定难度,所以我参考了网上的一些博客文章,并自己亲自摸索了一遍, ...

随机推荐

  1. Springboot对SpringMVC如何扩展配置

    原文地址:http://www.javayihao.top/detail/171 概述 Springboot在web层的开发基本都是采用Springmvc框架技术,但是Springmvc中的某些配置在 ...

  2. docker 指定版本rpm包安装

    1.docker rpm包下载地址 # https://download.docker.com/linux/centos/7/x86_64/stable/Packages/ 2.下载rpm包 # wg ...

  3. 你的首个golang语言详细入门教程 | your first golang tutorial

    本文首发于个人博客https://kezunlin.me/post/a0fb7f06/,欢迎阅读最新内容! your first golang tutorial go tutorial version ...

  4. QLineEdit限制数据类型——只能输入浮点型数

    前言 最近做了一个小的上位机,要通过串口来下发几个时间参数,为了防止误输入,产生不必要的麻烦,我把输入范围限制在0-680的浮点型数据,支持小数点后2位.学习了一下QLineEdit类是如何限制输入类 ...

  5. 浅谈Httpmodules

    HttpModule是ASP.NET过滤器,可以理解为HTTP请求的必经之地我们只要实现IHttpModule接口,就可以取代HttpModule namespace BookShop.Handler ...

  6. netcore3.0配置跨域

    netcore3.0框架已集成了Microsoft.AspNetCore.Mvc.Cors包,因此不需要单独引用. 在ConfigureServices中添加Cors策略服务 services.Add ...

  7. leaflet 实现克里金插值功能(附源码下载)

    前言 leaflet 入门开发系列环境知识点了解: leaflet api文档介绍,详细介绍 leaflet 每个类的函数以及属性等等 leaflet 在线例子 leaflet 插件,leaflet ...

  8. Jupyter Notebooks的安装和使用介绍

    最近又开始重新学习Python,学习中使用到了一款编辑器Jupyter Notebooks ,非常想安利给初学python的同学.注:本文内容仅针对windows环境下安装和配置Jupyter Not ...

  9. Django 模板变量之 forloop

    1. 模板变量之forloop.counter:从1开始自增1 模板代码如下: {% for row in v %} <tr> <td>{{forloop.counter}}& ...

  10. (办公)访问其他系统接口httpClient,异步访问

    访问其他系统接口httpClient,但是都是同步的,同步意味当前线程是阻塞的,只有本次请求完成后才能进行下一次请求;异步意味着所有的请求可以同时塞入缓冲区,不阻塞当前的线程; httpClient请 ...