C#动态解析XML数据DynamicXml帮助类库

DynamicXmlHelper运用Dynamic特性将xml字符串自动转换为Dynamic Object实现动态解析XML


DynamicXml 全称为DynamicXmlHelper
中文简称:动态Xml解析帮助类
适用版本:.NET Framework 4.0以上版本(包含.NET4.0)
核心技术:运用Dynamic特性将xml字符串自动转换为Dynamic Object实现动态解析XML

DynamicXmlHelper源码下载


using System;
using System.Collections.Generic;
using System.Linq;
using System.Dynamic;
using System.Xml.Linq;
using System.Collections;

public class DynamicXml : DynamicObject, IEnumerable
{
    /*
     * DynamicXml 全称为DynamicXmlHelper
     * 中文简称:动态Xml解析帮助类
     * 适用版本:.NET Framework 4.0以上版本(包含.NET4.0)
     * 核心技术:运用Dynamic特性将xml字符串自动转换为Dynamic Object实现动态解析XML
     */
    private readonly List<XElement> _elements;

    public DynamicXml(string text)
    {
        var doc = XDocument.Parse(text);
        _elements = new List<XElement> { doc.Root };
    }

    protected DynamicXml(XElement element)
    {
        _elements = new List<XElement> { element };
    }

    protected DynamicXml(IEnumerable<XElement> elements)
    {
        _elements = new List<XElement>(elements);
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = null;
        if (binder.Name == "Value")
            result = _elements[0].Value;
        else if (binder.Name == "Count")
            result = _elements.Count;
        else
        {
            var attr = _elements[0].Attribute(XName.Get(binder.Name));
            if (attr != null)
                result = attr;
            else
            {
                var items = _elements.Descendants(XName.Get(binder.Name));
                if (items == null || items.Count() == 0) return false;
                result = new DynamicXml(items);
            }
        }
        return true;
    }

    public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
    {
        int ndx = (int)indexes[0];
        result = new DynamicXml(_elements[ndx]);
        return true;
    }

    public IEnumerator GetEnumerator()
    {
        foreach (var element in _elements)
            yield return new DynamicXml(element);
    }
}


原文链接:C#动态解析XML数据DynamicXml帮助类