本文提供一个操作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. 条款1:视C++为一个语言联邦

    C++是门多范式语言,至少包括面向过程,面向对象,泛型,函数式,元变成等. 但谨记,不要随意混合使用各种特性,为自己制定使用原则,针对不同项目.业务. 如: 类C风格编程:没有模板,没有异常,没有重载 ...

  2. Ubuntu cd

    查看目录文件内容 ./  or filename/file.* cd 返回用户主目录 ~,,,,,/home/user cd ..不管用 cd / 返回用户根目录 root

  3. jquery 动态添加的代码不能触发绑定事件

    今天发现jQuery对动态添加的元素不触发事件,比如blur.click事件等 参考文章证明了我的结论,并给出了原因及解决方案 原因:程序找不到动态添加的节点. 解决方案:在绑定父元素后的子元素 $( ...

  4. advance shading--BRDF

    其实,双向反射(reflect)分布函数(BRDF)是一个四元函数,这个函数最终只是计算一个比值,这个值确定了射入物体表面的光中有多少被物体表面反射,并最终被眼睛所看到.反射的愈多,眼睛收到的光强越大 ...

  5. 七大排序的个人总结(二) 归并排序(Merge

    七大排序的个人总结(二)   归并排序(Merge  归并排序(Merge Sort): 归并排序是一个相当“稳定”的算法对于其它排序算法,比如希尔排序,快速排序和堆排序而言,这些算法有所谓的最好与最 ...

  6. 五步打造APP节日主题设计:以Lofter新年图标设计为例

    我们需要做有依据,有逻辑,有理念的设计,需要发散思维,整合创意,严谨输出,让设计经得起推敲 前言 ​ 2018年春节已远去,一直想把Lofter新年Logo设计思路分享给大家,直到现在才整理出来,希望 ...

  7. 2018.07.08 hdu5316 Magician(线段树)

    Magician Problem Description Fantasy magicians usually gain their ability through one of three usual ...

  8. hdu-1061(快速幂)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1061 思路:快速幂 #include<iostream> #include<cstd ...

  9. 第一章:模型层model layer

    1.模型和字段 (1)基本的原则如下: 每个模型在Django中的存在形式为一个Python类 每个模型都是django.db.models.Model的子类 模型的每个字段(属性)代表数据表的某一列 ...

  10. 1024 Hello World

    哈哈,原来今天是程序员的节日啊,快乐咯,可是今天好冷好冷~~