操作XML
别人已经写过很好的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的更多相关文章
- Asp.Net 操作XML文件的增删改查 利用GridView
不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...
- php中通过DOM操作XML
DOM文档在js里早就接触过,知道DOM不但可以操作html文档,还可以操作XHTML,XML等文档,有着极强的通用性,下面我们通过两个小例子,看看在PHP中是如何用DOM操作XML文档的,和js中差 ...
- 使用dom4j操作XML
DOM4J介绍 DOM4J是使用Java语言编写的,用于读写及操作XML的一套组件,DOM4J同时具有DOM修改文件的优点和SAX读取快速的优点. DOM4J的使用 首先下载dom4j的JAR包,我用 ...
- 使用JDOM操作XML
JDOM介绍 JDOM是使用Java语言编写的,用于读写及操作XML的一套组件,Jdom同时具有DOM修改文件的优点和SAX读取快速的优点. JDOM的使用 首先下载JDOM的JAR包,本文使用的是j ...
- php : DOM 操作 XML
DOM 操作 XML 基本用法 XML文件: person.XML <?xml version="1.0" encoding="utf-8" ?> ...
- Strus2第一次课:dom4j操作xml
先从底层的xml操作技术记录: 当我们新建一个项目,什么架包都没加入的时候,java提供了 org.w3c.dom给我们操作xml里面的元素 import org.w3c.dom.Document; ...
- .NET 操作XML
在C#.net中如何操作XML 需要添加的命名空间: using System.Xml; 定义几个公共对象: XmlDocument xmldoc ; XmlNode xmlnode ; XmlEle ...
- php操作xml
最近计划写个人的小网站,一系列原因选择了用php来写,最大的问题就是虽然php很流行,但我从来没有接触过php,看了一个多星期的基本语法后做些小练习热热身,但是期间是各种问题啊,主要是对php不熟悉, ...
- JavaScript操作XML
JavaScript操作XML (一) JavaScript操作XML是通过XML DOM来完成的.那么什么是XML DOM呢?XML DOM 是: 用于 XML 的标准对象模型 用于 XML 的标准 ...
- C#操作XML方法集合
一 前言 先来了解下操作XML所涉及到的几个类及之间的关系 如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家 * 1 XMLElement 主要是针对节点的一些属性进行操 ...
随机推荐
- pycharm远程调试服务器
1.下载专业版pycharm并激活 https://blog.csdn.net/weixin_39332299/article/details/79692283 2.创建项目,设置解释器时,选择SSH ...
- Lesson 3-2 语句:循环语句
3.2 循环语句 3.2.1 while 循环语句 --- while 语句包含:关键字while.条件.冒号.while子句(代码块). --- 执行while 循环,首先判断条件是否为真,如果为假 ...
- UGUI中粒子特效与UI的遮挡问题
问题背景: 在做主线任务时发现完成任务后的特效显示穿透上面的UI层,不美观,策划不乐意了,抓紧解决下 解决思路: 首先讲下影响渲染顺序的因素: 能够影响渲染顺序的因素有:1.Camera Depth ...
- 【java】java基本用法记录
java用法总结 计时 long startTime = System.nanoTime(); solution.process(inputFile); long endTime = System.n ...
- js-将文本复制到剪切板
// 将文本复制到剪切板 var clipboard2 = new ClipboardJS('.add_wx_guide_float', { text: function(trigger) { ret ...
- 微信小程序rich-text 文本首行缩进和图片居中
微信小程序开发使用rich-text组件渲染html格式的代码,常常因为不能自定义css导致文本不能缩进,以及图片不能居中等问题,这里可以考虑使用js的replace方法,替换字符串,然后在渲染的同时 ...
- 在js中获取上传图片的宽度和高度
Html: <input type="file" id="MapUploadTd" onchange="getMapPictureSize(th ...
- 运行Scrapy程序时出现No module named win32api问题的解决思路和方法
有小伙伴在群里边反映说在使用Scrapy的时候,发现创建项目一切顺利,但是在执行Scrapy爬虫程序的时候却出现下列报错:“No module named win32api”,如下图所示,但是不知道怎 ...
- 一个二维码-->网址-->iOS/Android跳转
view-source:https://dpx.shopo.com.cn/down.html lmxmn117:~ will.wei$ curl https://dpx.shopo.com.cn/do ...
- mysql 和 sqlserver sql差异比较
mysql:select * from table_name limit 100,200;--取出从100到200的数据 获取时间:mysql:now() mysql tinyint(0,1) → b ...