别人已经写过很好的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 主要是针对节点的一些属性进行操 ...
随机推荐
-
How Spring Boot Autoconfiguration Magic Works--转
原文地址:https://dzone.com/articles/how-springboot-autoconfiguration-magic-works In my previous post &qu ...
-
hdu.1429.胜利大逃亡(续)(bfs + 0101011110)
胜利大逃亡(续) Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total S ...
-
Transact-SQL 示例 - UPDATE中使用INNER JOIN
一般情况下博主已经对在SELECT语句当中使用INNER JOIN非常娴熟,但在UPDATE当中使用INNER JOIN的场景就为数不多了.以下博主将为你介绍在UPDATE场景当中使用INNER JO ...
-
通用js类库
/* 其它通用函数 */$(function() { // var General = function() { var _self = this; /* 写 cookie 操作 */ _self.S ...
-
连接db2数据库时NumberFormatException异常的解决方式
连接db2数据库时报异常:java.lang.NumberFormatException: For input string: "A" from a DB2 JDBC(JCC) j ...
-
Java [Leetcode 58]Length of Last Word
题目描述: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return ...
-
AjaxPro使用方法
无意中看到同事用AjaxPro用,看到很不错,特长是前后台传输数据特别方便. 最好的教材就是拿到就可以用,方便大家. 以前数据传输用FORM提交,或者在前台用JASON拼接然后通过AJAX方式提交.总 ...
-
FlowLayoutPanel autowrapping doesn&#39;t work with autosize
There is no such thing like impossible in software development. Impossible just takes longer. I've i ...
-
ajax调用webservice(二) 跨域。
所需工具与项目结构同(一). service.asmx中代码如下: using System; using System.Collections.Generic; using System.Web; ...
-
DirectSound---输出设备基本操作(枚举、查询等)
DirectSound是DirectX组件之一,提供了对音频设备的捕获和播放能力,同时它也是唯一几个支持Xp系统的音频技术之一. DirectSound主要有以下特点: 优点: 播放音频低延迟. 硬件 ...