别人已经写过很好的XML辅助类,可以直接引用后使用;

我这里自己写一个xml的操作类,目前能实现的是对一个不含集合的类可以操作,含集合的类无法将集合里的数据读取出来,

首先定义一个XML特性,用于区分属性和标签

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*********************************************************************
唯一标识:098b09ce-0d0e-4a87-ba21-2adf20d951b5
版本号:v1.0.0.0
CLR版本:4.0.30319.42000
======================================================================
创建人: liusg
创建时间:2018/7/6 11:10:25
**********************************************************************/
namespace CrtXElement
{
/// <summary>
/// XML特性
/// </summary>
public class CrtXmlAttribute: Attribute
{
/// <summary>
/// 标记为属性
/// </summary>
public bool Property { get; set; }
/// <summary>
/// 标记为唯一标识键
/// </summary>
public bool Key { get; set; } }
}

写一个测试用的对象类(类里面不能含集合)

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*********************************************************************
唯一标识:63818db9-6d98-45b9-8c3f-0545f8f4f9b3
版本号:v1.0.0.0
CLR版本:4.0.30319.42000
======================================================================
创建人: liusg
创建时间:2018/7/6 11:08:44
**********************************************************************/
namespace CrtXElement
{
public class CrtModel
{
[CrtXml(Key=true,Property =true)]
public int Key { get; set; }
public string Name { get; set; }
} } 然后是实现对XML的操作方式,
 using CrtGloble;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
/*********************************************************************
唯一标识:d9c52e14-e9d1-4152-9ded-25b25383247e
版本号:v1.0.0.0
CLR版本:4.0.30319.42000
======================================================================
创建人: liusg
创建时间:2018/7/6 13:19:05
**********************************************************************/
namespace CrtXElement
{
public class CxeDemo<T> where T : new()
{
public string _FilePath = "/";
private XElement root;
public void Load(string filePath, string fileName)
{
this._FilePath = Path.Combine(filePath, fileName);
if (string.IsNullOrEmpty(filePath))
throw new Exception("无效的路径"); if (string.IsNullOrEmpty(fileName) || !fileName.Contains('.'))
throw new Exception("无效的文件名"); if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath); try
{ if (!File.Exists(Path.Combine(filePath, fileName)))
root = new XElement($"XML");
else root = XElement.Load(Path.Combine(filePath, fileName));
}
catch (Exception e)
{ root = new XElement($"XML");
}
if (root == null)
{
root = new XElement($"XML");
} }
private bool Save()
{
if (root == null)
return false; try
{
root.Save(_FilePath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
return true;
} public List<T> GetList()
{
List<T> list = new List<T>();
var xmlList = root.Elements();
var _type = typeof(T);
foreach (XElement item in xmlList)
{
var model = new T();
foreach (var Propertie in _type.GetProperties())
{
if (Propertie.IsDefined(typeof(CrtXmlAttribute), true))
{
var Attributes = (CrtXmlAttribute)Propertie.GetCustomAttributes(false).FirstOrDefault();
if (Attributes == null)
{
var attrValue = item.Element(Propertie.Name);
if (attrValue != null)
Propertie.SetValue(model, GetTypeVal(attrValue.Value, Propertie.PropertyType));
else
Propertie.SetValue(model, GetTypeVal("", Propertie.PropertyType));
}
else
{
if (Attributes.Property)
{
var attrValue = item.Attribute(Propertie.Name);
if (attrValue != null)
Propertie.SetValue(model, GetTypeVal(attrValue.Value, Propertie.PropertyType));
else
Propertie.SetValue(model, GetTypeVal("", Propertie.PropertyType));
}
else
{
var attrValue = item.Element(Propertie.Name);
if (attrValue != null)
Propertie.SetValue(model, GetTypeVal(attrValue.Value, Propertie.PropertyType));
else
Propertie.SetValue(model, GetTypeVal("", Propertie.PropertyType));
}
}
}
else
{
var attrValue = item.Element(Propertie.Name);
if (attrValue != null)
Propertie.SetValue(model, GetTypeVal(attrValue.Value, Propertie.PropertyType));
else
Propertie.SetValue(model, GetTypeVal("", Propertie.PropertyType));
}
}
list.Add(model);
}
return list;
}
public void Add(T model)
{
var _type = typeof(T);
XElement newel = new XElement(_type.Name);
foreach (var item in _type.GetProperties())
{
if (item.IsDefined(typeof(CrtXmlAttribute), true))
{
var Attributes = (CrtXmlAttribute)item.GetCustomAttributes(false).FirstOrDefault();
if (Attributes == null)
{
XElement net = new XElement(item.Name);
net.SetValue(item.GetValue(model));
newel.Add(net);
}
else
{
if (Attributes.Property)
{
newel.SetAttributeValue(item.Name, item.GetValue(model)); }
else
{
XElement net = new XElement(item.Name);
net.SetValue(item.GetValue(model));
newel.Add(net);
}
}
}
else
{
XElement net = new XElement(item.Name);
net.SetValue(item.GetValue(model));
newel.Add(net);
}
}
root.Add(newel); Save(); } public void Update(T model)
{
if(Delete(model))
{
Add(model);
}
}
public bool Delete(Func<T,bool> where)
{
var model = GetList().Where(where).FirstOrDefault();
if (model == null)
return false;
return Delete(model);
}
public bool Delete(T model)
{
var _type = typeof(T);
foreach (var item in _type.GetProperties())
{
var Attributes = (CrtXmlAttribute)item.GetCustomAttributes(false).FirstOrDefault();
if (Attributes != null)
{
if (Attributes.Key)
{
var rootFist = root.Elements(_type.Name).FirstOrDefault(p => p.Attribute(item.Name).Value == item.GetValue(model).ToString());
if (rootFist != null)
{
root.Elements(_type.Name).Where(p => p == rootFist).Remove();
return true; }
}
}
}
return false;
} object GetTypeVal(object obj, Type ty)
{
var val = ty.Name;
if (val == "Int32")
{
return obj.ToInt_V();
}
else if (val == "String")
{
return obj.ToString_V();
}
else if (val == "DateTime")
{
return obj.ToDateTime_V();
}
else if (val == "Double")
{
return obj.ToDouble_V();
}
else if (val == "Boolean")
{
return obj.ToBoolean_V();
}
else if (val == "Decimal")
{
return obj.ToDecimal_V();
}
else if (val == "Int64")
{
return obj.ToLong_V();
}
else if (val == "UInt32")
{
return obj.ToUint_V();
}
else
{
return obj.ToString_V();
}
}
}
} 接下来就是测试数据
 using CrtGloble;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CrtXElement
{
class Program
{
static void Main(string[] args)
{
CxeDemo<CrtModel> demo = new CxeDemo<CrtModel>();
demo.Load(@"F:\", "demo.txt");
//demo.Add(new CrtModel
//{
// Key = 23,
// Name = "ddd"
//});
//demo.Add(new CrtModel
//{
// Key = 24,
// Name = "ddd"
//});
//demo.Update(new CrtModel
//{
// Key = 24,
// Name = "sdfgserg",
//});
//demo.Update(new CrtModel
//{
// Key = 240,
// Name = "sdfgserg",
//});
foreach (var item in demo.GetList())
{
Console.WriteLine(item.ToProperties_V());
} }
}
}
xml文件


操作XML的更多相关文章

  1. Asp.Net 操作XML文件的增删改查 利用GridView

    不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...

  2. php中通过DOM操作XML

    DOM文档在js里早就接触过,知道DOM不但可以操作html文档,还可以操作XHTML,XML等文档,有着极强的通用性,下面我们通过两个小例子,看看在PHP中是如何用DOM操作XML文档的,和js中差 ...

  3. 使用dom4j操作XML

    DOM4J介绍 DOM4J是使用Java语言编写的,用于读写及操作XML的一套组件,DOM4J同时具有DOM修改文件的优点和SAX读取快速的优点. DOM4J的使用 首先下载dom4j的JAR包,我用 ...

  4. 使用JDOM操作XML

    JDOM介绍 JDOM是使用Java语言编写的,用于读写及操作XML的一套组件,Jdom同时具有DOM修改文件的优点和SAX读取快速的优点. JDOM的使用 首先下载JDOM的JAR包,本文使用的是j ...

  5. php : DOM 操作 XML

    DOM 操作 XML 基本用法 XML文件: person.XML <?xml version="1.0" encoding="utf-8" ?> ...

  6. Strus2第一次课:dom4j操作xml

    先从底层的xml操作技术记录: 当我们新建一个项目,什么架包都没加入的时候,java提供了 org.w3c.dom给我们操作xml里面的元素 import org.w3c.dom.Document; ...

  7. .NET 操作XML

    在C#.net中如何操作XML 需要添加的命名空间: using System.Xml; 定义几个公共对象: XmlDocument xmldoc ; XmlNode xmlnode ; XmlEle ...

  8. php操作xml

    最近计划写个人的小网站,一系列原因选择了用php来写,最大的问题就是虽然php很流行,但我从来没有接触过php,看了一个多星期的基本语法后做些小练习热热身,但是期间是各种问题啊,主要是对php不熟悉, ...

  9. JavaScript操作XML

    JavaScript操作XML (一) JavaScript操作XML是通过XML DOM来完成的.那么什么是XML DOM呢?XML DOM 是: 用于 XML 的标准对象模型 用于 XML 的标准 ...

  10. C#操作XML方法集合

    一 前言 先来了解下操作XML所涉及到的几个类及之间的关系  如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家 * 1 XMLElement 主要是针对节点的一些属性进行操 ...

随机推荐

  1. .Net core----使用容联云短信推送

    一直在忙于写接口,也没有时间去好好的整理的一片文档,写一篇经常的用到的短信推送案例 还是比较喜欢干货  作为有个程序员 有时候复制粘贴习惯了   实在的还是比较实在 比如能用复制解决的为什么不用复制 ...

  2. JDBC编程六部曲

    今天初学jdbc,明白了大致的编程流程,在此总结一下: JDBC编程可以分为六步——六部曲: * 第一步:注册驱动. * 1.1 获取驱动对象 * 1.2 注册驱动 * 第二步:获取数据库连接 * 第 ...

  3. a标签锚点平滑跳转

    一.创建锚点 <div class="header" id="top">//终点标签,添加一个id <a href="#top&qu ...

  4. 总结web自动化测试页面常用字段的定位方法

    在一次编写web自动脚本时,突然想到web页面常有的字段有:输入框,按钮,富文本输入框,下拉框选项,弹窗,表格,上传文件以及时间插件,以下总结的没有编写时间插件的用例了!以后碰到再更新, 以下是蹩脚代 ...

  5. CentOS7像外部163邮箱发送邮件

    我们在运维过程中,为了随时了解服务器的工作状态,出现问题随时提醒,像个人邮箱发送邮件是必须的,但是刚刚安装好的系统是无法发送邮件的.需要们进行一些配置和程序的安装,我安装完系统后,自带mail12.5 ...

  6. 奇葩最小生成树--->走廊泼水节(tyvj1391)

    题目描述 话说,中中带领的OIER们打算举行一次冬季泼水节,当然这是要秘密进行的,绝对不可以让中中知道.不过中中可是老江湖了,当然很快就发现了我们的小阴谋,于是他准备好水枪迫不及待的想要加入我们了. ...

  7. JVM内存结构--新生代及新生代里的两个Survivor区(下一轮S0与S1交换角色,如此循环往复)、常见调优参数

    一.为什么会有年轻代 我们先来屡屡,为什么需要把堆分代?不分代不能完成他所做的事情么?其实不分代完全可以,分代的唯一理由就是优化GC性能.你先想想,如果没有分代,那我们所有的对象都在一块,GC的时候我 ...

  8. 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。

    /** 转换成XML格式字符串 **/ public static String doXMLStr(Map<String, String> map) { StringBuffer xml_ ...

  9. python 字典、列表、字符串 之间的转换

    1.列表与字符串转换 1)列表转字符串: 将列表中的内容拼接成一个字符串 将列表中的值转成字符串 2)字符串转列表: 用eval转换 将字符串每个字符转成列表中的值 将字符串按分割成列表 2.列表与字 ...

  10. springboot+freemarker毕业设计项目错误合集

    1.springboot的主程序类必须在最外层. 换句话说,报错: This application has no explicit mapping for /error, so you are se ...