C#操作Xml树的扩展类
本文提供一个操作Xml树的扩展类,与将xml字符串直接映射成实体对象的使用方法,供大家参考,学习。
下面附上源码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using WoT.Infrastructure.Helper.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml.Serialization; namespace WoT.Infrastructure.Helper.Xml
{
/// <summary>
/// 操作Xml树的扩展类
/// Author: Jacky
/// </summary>
public static class XmlExpand
{ /// <summary>
/// 锁对象
/// </summary>
private static object objLock = new object(); /// <summary>
/// 获取路径的值。如果不存在则返回defaultValue 路径用/隔开
/// 支持获取同名同级节点中的某个,格式: elementName[index] 从0开始
/// </summary>
public static string GetValue(this XElement element, string xPath, string defaultValue = null)
{
element = element.GetElement(xPath);
return element == null ? defaultValue : element.Value;
} /// <summary>
/// 获取属性值 如果不存在则返回defaultValue
/// </summary>
public static string GetAttributeValue(this XElement element, string name)
{
if (element.Attribute(name) == null) return null;
string value = element.Attribute(name).Value;
return value;
} /// <summary>
/// 获取路径的节点。如果不存在则返回defaultValue 路径用/隔开
/// 支持获取同名同级节点中的某个,格式: elementName[index] 从0开始
/// </summary>
public static XElement GetElement(this XElement element, string xPath)
{
Regex regex = new Regex(@"(?<Name>.*)\[(?<Index>\d+)\]", RegexOptions.IgnoreCase);
try
{
foreach (string tag in xPath.Split('/'))
{
if (regex.IsMatch(tag))
{
string tagName = regex.Match(tag).Groups["Name"].Value;
int index = int.Parse(regex.Match(tag).Groups["Index"].Value);
element = element.Elements(tagName).ToArray()[index];
}
else
{
element = element.Element(tag);
}
if (element == null) return null; }
}
catch (Exception ex)
{
throw new Exception(ex.Message + "\n" + xPath);
}
return element; } /// <summary>
/// 两个XML合并 把obj拥有而root没有的节点和属性复制给root
/// </summary>
/// <param name="root">原始的对象</param>
/// <param name="obj"></param>
public static XElement Merger(this XElement root, XElement obj)
{
XmlMerger(root, obj);
return root;
} /// <summary>
/// 递归对比两个节点,把obj拥有而root没有的节点复制到root中
/// </summary>
/// <param name="root"></param>
/// <param name="obj"></param>
private static void XmlMerger(XElement root, XElement obj)
{
foreach (XElement element in obj.Elements())
{
var childElements = root.Elements(element.Name); if (childElements.Count() == )
{
root.Add(element);
}
else if (childElements.Count() == ) // 有且只有一个同名节点才启动复制递归规则
{
XElement childElement = childElements.First();
foreach (XAttribute attribute in element.Attributes())
{
if (childElement.Attributes(attribute.Name).Count() == )
childElement.SetAttributeValue(attribute.Name, attribute.Value);
}
XmlMerger(childElement, element);
}
}
} /// <summary>
/// 遍历所有的子元素中包含名称的节点
/// </summary>
/// <param name="tagName"></param>
/// <returns></returns>
public static List<XElement> GetElements(this XElement root, params string[] tagName)
{
List<XElement> list = new List<XElement>();
GetElements(root, list, tagName);
return list;
} private static void GetElements(XElement root, List<XElement> list, params string[] tagName)
{
foreach (XElement el in root.Elements())
{
if (tagName.Contains(el.Name.ToString()))
{
list.Add(el);
}
GetElements(el, list, tagName);
}
} /// <summary>
/// XML转实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strXML"></param>
/// <returns></returns>
public static T DESerializer<T>(string strXML) where T : class
{
try
{
using (StringReader sr = new StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
return null;
}
} /// <summary>
/// 从XML字符串中反序列化对象
/// </summary>
/// <typeparam name="T">结果对象类型</typeparam>
/// <param name="xml">包含对象的XML字符串</param>
/// <param name="encoding">编码方式</param>
/// <returns>反序列化得到的对象</returns>
public static T XmlDeserialize<T>(string xml, Encoding encoding)
{
if (string.IsNullOrEmpty(xml))
throw new ArgumentNullException("xml is null");
if (encoding == null)
throw new ArgumentNullException("encoding"); XmlSerializer mySerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(xml)))
{
using (StreamReader sr = new StreamReader(ms, encoding))
{
return (T)mySerializer.Deserialize(sr);
}
}
} }
}
操作Xml树的扩展类
将xml字符串直接映射成实体对象

一段代码搞定
PS:扫描下方二维码或点击链接,加入QQ群


C#操作Xml树的扩展类的更多相关文章
- ***codeigniter操作xml(Simplexml第三方扩展)
This Simplexml class provides an alternative implementation of the SimpleXML API that works under PH ...
- 一个用 C# 实现操作 XML 文件的公共类代码
using System; using System.IO; using System.Data; using System.Xml; using System.Xml.XPath; namespac ...
- php操作xml详解
XML是一种流行的半结构化文件格式,以一种类似数据库的格式存储数据.在实际应用中,一些简单的.安全性较低的数据往往使用 XML文件的格式进行存储.这样做的好处一方面可以通过减少与数据库的交互性操作提高 ...
- C#操作XML配置文件
代码为C#操作xml配置文件的范例类,函数SetValue用于向配置文件写入一个值,GetValue用于根据Key获取相应值。这种方法的配置文件不需要手动创建,程序在运行后会自动处理创建。 注意:1. ...
- C#操作xml完整类文件
C#操作xml完整类文件 xml_oper.cs using ...System; using System.Data; using System.Web; using System.Xml; /** ...
- 使用dom4j类操作xml文档
dom4j操作xml数据 1.Document对象相关 ①读取XML文件,获得document对象. SAXReader reader = new SAXReader(); Document docu ...
- XML学习笔记(2)--dom4j操作XML
1. 介绍(四种方式的比较这部分转载自:http://www.blogjava.net/xcp/archive/2010/02/12/312617.html) 1)DOM(JAXP Crimson解析 ...
- Delphi操作XML
Delphi操作XML Delphi操作XMl,只要使用 NativeXml.我是用的版本是4..NativeXML的使用方法比较简单,但是功能很强大. XE2的话,要在simdesign.inc后面 ...
- Delphi操作XML - 冰雪傲骨
Delphi操作XMl,只要使用 NativeXml.我是用的版本是4..NativeXML的使用方法比较简单,但是功能很强大. XE2的话,要在simdesign.inc后面加上: // Delph ...
随机推荐
- iOS 处理cell选中时背景颜色消息问题
在cell上添加子控件,在我们点击或者长按的时候,如果子控件有背景颜色,这时候背景颜色就会没有了,这个时候产品经理过来一顿怼,
- error: In function ‘void* opencv_showimg(void*)’:
今天这个问题折磨了我一下午,终于知道是为什么了,心酸历程.....赶紧来记录一下 错误: /home/wj/workspace/Loitor_VI_Sensor_SDK_V1./SDK/src/cam ...
- Paypal支付
<!--Paypal支付数据开始--> <input type="hidden" name="charset" value="utf ...
- Mina入门:mina版之HelloWorld[z]
Mina入门:mina版之HelloWorld [z] 一,前言: 在完成上篇文章<Mina入门:Java NIO框架Mina.Netty.Grizzly简介与对比>之后,我们现在可以正式 ...
- 获取url路径中的参数
简介 运用js的时候,我们有时可能会有这样的需求,就是想要获取浏览器地址栏指定的一项参数,形如:https://i.cnblogs.com/EditPosts.aspx?postid=8628413& ...
- phpstrom+xdebug配置
1.确认是否安装了xdebug 2.在php.ini文件中配置如下 [xdebug] zend_extension="D:\wamp\php-5.6.2-x64\ext\php_xdebug ...
- 利用HBuilder打包前端开发webapp为apk
转载 标签: apk / 打包 / vue 现在的前端开发可谓是,百花齐放啦,什么都可以做,只有想不到没有做不到的,今天就简单的介绍用vue,ng或者是react开发的单页应用如何打包为apk,在移动 ...
- 在mac console下 执行c++文件
1 $ g++ -o NewFileName OldFileName.cpp -o is the letter O not zero NewFileName will be your executab ...
- oracle建存储过程
进入plsql命令行 [10:42:10 liuyi@localhost]/home/liuyi>sqlplus demo/demo@180.200.3.129/meboss 连接串格式:用户名 ...
- Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享
Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享 支付宝十年账单上的数字有点吓人,但它统计的项目太多,只是想看看到底单纯在淘宝上支出了多少,于是写了段脚本,统计任意时间段淘宝订单的消费情况,看 ...