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 ...
随机推荐
- swift OC混编工程,xcode断点调试,控制台左侧只有变量名称不显示值,右侧输入po命令,打印除一堆提示
断点调试 (lldb) po 变量名warning: Swift error in module 项目名.Debug info from this module will be unavailable ...
- 25-javaweb接入支付宝支付接口
想熟悉支付宝接口支付,后面可能会用,不如在课设中试试手.好吧听说支付宝不微信支付要简单些,就拿支付宝的先练下手吧. 基本学习流程,百度一下,找篇博客看下. 推荐下面这个篇博客,讲的挺好的,复制过来. ...
- Halcon一维码和二维码的解码步骤和技巧——第11讲
针对Halcon中一维码和二维码的解码,我分别写了两篇文章,参见: <Halcon的一维条码解码步骤和解码技巧>:https://www.cnblogs.com/xh6300/p/1048 ...
- 在 Microsoft Dynamics 365 Online中如何调试Plugins in
How to debug plugins in Microsoft Dynamics 365 Online 调试方式请查阅https://www.linkedin.com/pulse/how-debu ...
- cookie、session、token区分
https://www.cnblogs.com/moyand/p/9047978.html http://www.cnblogs.com/JamesWang1993/p/8593494.html Co ...
- StartServiceCtrlDispatcher
服务程序通常编写成控制台类型的应用程序,总的来说,一个遵守服务控制管理程序接口要求的程序 包含下面三个函数: 1.服务程序主函数(main):调用系统函数 StartServiceCtrlDispat ...
- How to Install and Configure Bind 9 (DNS Server) on Ubuntu / Debian System
by Pradeep Kumar · Published November 19, 2017 · Updated November 19, 2017 DNS or Domain Name System ...
- 创建WRAPPER时, SQL20076N 未对指定的操作启用数据库的实例。
您可以通过运行DB2 UPDATE DBM CFG USING FEDERATED YES来设置这个参数.修改这个参数后,必须重新启动实例才会生效(DB2STOP/DB2START).所以你会出现你的 ...
- IC向管理者角色转换
1. 虽然你认为自己已经想明白怎么干,但还是从怎么干回归到要解决的问题,抛给正确的人(应该对这些问题负责的人),引导他们想出问题的答案. 给别人机会和空间,帮助他们成长: 人们对自己“想”出的方案更有 ...
- 2018.07.08 POJ 2481 Cows(线段树)
Cows Time Limit: 3000MS Memory Limit: 65536K Description Farmer John's cows have discovered that the ...