本文提供一个操作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树的扩展类的更多相关文章

  1. ***codeigniter操作xml(Simplexml第三方扩展)

    This Simplexml class provides an alternative implementation of the SimpleXML API that works under PH ...

  2. 一个用 C# 实现操作 XML 文件的公共类代码

    using System; using System.IO; using System.Data; using System.Xml; using System.Xml.XPath; namespac ...

  3. php操作xml详解

    XML是一种流行的半结构化文件格式,以一种类似数据库的格式存储数据.在实际应用中,一些简单的.安全性较低的数据往往使用 XML文件的格式进行存储.这样做的好处一方面可以通过减少与数据库的交互性操作提高 ...

  4. C#操作XML配置文件

    代码为C#操作xml配置文件的范例类,函数SetValue用于向配置文件写入一个值,GetValue用于根据Key获取相应值。这种方法的配置文件不需要手动创建,程序在运行后会自动处理创建。 注意:1. ...

  5. C#操作xml完整类文件

    C#操作xml完整类文件 xml_oper.cs using ...System; using System.Data; using System.Web; using System.Xml; /** ...

  6. 使用dom4j类操作xml文档

    dom4j操作xml数据 1.Document对象相关 ①读取XML文件,获得document对象. SAXReader reader = new SAXReader(); Document docu ...

  7. XML学习笔记(2)--dom4j操作XML

    1. 介绍(四种方式的比较这部分转载自:http://www.blogjava.net/xcp/archive/2010/02/12/312617.html) 1)DOM(JAXP Crimson解析 ...

  8. Delphi操作XML

    Delphi操作XML Delphi操作XMl,只要使用 NativeXml.我是用的版本是4..NativeXML的使用方法比较简单,但是功能很强大. XE2的话,要在simdesign.inc后面 ...

  9. Delphi操作XML - 冰雪傲骨

    Delphi操作XMl,只要使用 NativeXml.我是用的版本是4..NativeXML的使用方法比较简单,但是功能很强大. XE2的话,要在simdesign.inc后面加上: // Delph ...

随机推荐

  1. jQuery之双下拉框

    双下拉框要实现的效果,实际上就是左边下拉选择框里的内容,可以添加到右边,而右边同理.写了个简单的例子,来说明一下. 代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...

  2. 让php支持多线程,win下安装pthreads

    1.检查PHP版本是否支持线程安全 在phpinfo()的显示页中,搜索Thread Safety,如果是enabled,则PHP版本是线程安全的. 2.在http://windows.php.net ...

  3. Vmware迁移以后eth0消失,无法上网

    一个再普通不过的大神帮助小菜做虚拟机镜像的事情: 小张:帮我做个Vmware下的Ubuntu镜像吧,大神. 小黄:好啊,等我一下,下午发给你. 经过一番操作,小黄顺利的做出了一个虚拟机操作系统 小黄: ...

  4. ubuntu关闭防火墙

    https://jingyan.baidu.com/article/73c3ce283ee2c1e50343d9f6.html

  5. 【原型实战】分分钟搞定Unsplash网站原型设计

    网站原型设计是我们在设计网页过程中必不可少的一步,激烈的市场竞争让我们不得不对产品进行快速迭代,如何高速有效的进行原型设计成为了设计师头疼的问题.本文将以unsplash网站为实例,教大家快速搞定we ...

  6. 新电脑的操作系统win10的所有设置问题汇总

    上来改的win7发现很多驱动没法装,装了也不能用,后来只能改win10了,另外win7的风扇声音也很大. 1.关闭win10自动更新.在服务里面禁用winupdate 2.注销改成了点头像,然后点注销 ...

  7. linux 常用压缩打包和解压命令

    ## zcvf gzip jcvf bzip2 gunzip  tar zxvf  jxvf  

  8. linux 操作系统rz sz 快速上传和下载文件

    ## Centos  安装  rz  sz yum install lrzsz ### Ubuntu  安装 apt-get install lrzsz

  9. ajax序列化表单,再也不用通过data去一个个的传值了

    jQuery的serialize()方法通过序列化表单值,创建URL编码文本字符串,我们就可以选择一个或多个表单元素,也可以直接选择form将其序列化 这样,我们就可以把序列化的值传给ajax()作为 ...

  10. 2018.06.27Going Home(二分图匹配)

    Going Home Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 24716 Accepted: 12383 Descript ...