操作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 主要是针对节点的一些属性进行操 ...
随机推荐
- MAC本apache+php配置虚拟域名时踩的坑
昨天在调试Mac自带的Apache+PHP配置域名时,调试的让我怀疑人生.顿时心里一万个草泥马,我就是配置个虚拟域名啊,这么让我受伤 . 1 首先检查一下Apache是否开启, qutao@bogon ...
- 使用JMeter的HTTP代理服务器录制app脚本
1.添加一个线程组 2.添加一个HTTP代理服务器 3.设置手机网络连接 4.手机安装证书 a.进入jmeter安装目录,在bin目录下找到ApacheJMeterTemporaryRootCA.cr ...
- webpack4与babel配合使es6代码可运行于低版本浏览器
使用es6+新语法编写代码,可是不能运行于低版本浏览器,需要将语法转换成es5的.那就借助babel7转换,再加上webpack打包,实现代码的转换. 转换包括两部分:语法和API let.const ...
- Semantic difference between object expressions and declarations
object expressions are executed (and initialized) immediately, where they are used; object declarati ...
- keras安装-【老鱼学keras】
为何要用keras? 两个字:简单. Keras让深度学习像搭建积木一样方便地来进行,使前面的tensorflow能够更加方便地使用. 虽然还有其它更多的理由,比如:Keras 支持多个后端引擎,不会 ...
- pycharm远程debug(内网环境,跳板机)
1.设置隧道 工具: secureCRT 1.新建跳板机连接session 2.选择刚建好的session --> Properties --> Port Forwarding --> ...
- hibernate-release-5.2.9.Final
链接:https://pan.baidu.com/s/1UaoaaXb5C9gJp3Yu7sjUVQ 提取码:orgx
- 动态网页获取ajax,post方法,url里面不直接显示参数
记录一下,爬去ajax数据时,需要注意一下是post方法还是get方法,get方法就正常做就行了,但是post方法的话,需要这样,如下 a = requests.request('post',url) ...
- sql查询单表之中大于2条的数据
SELECT COUNT(字段)AS COUNT,字段FROM 表名 GROUP BY 字段 HAVING COUNT >=
- Hive基础测试操作
一.Hive测试 1.查看数据库 show databases; 2.使用某个数据库,如默认数据库 user default; 3.创建表 create table if not exist itst ...