码迷,mamicode.com
首页 > Web开发 > 详细

.net4 dynamic parse xml

时间:2016-04-13 11:05:23      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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

namespace DynamicReadXml
{
    public static class ExpandoXML
    {
        public static dynamic AsExpando(this XDocument xDocument)
        {
            return CreateExpando(xDocument.Root);
        }

        private static dynamic CreateExpando(XElement element)
        {
            var result = new ExpandoObject() as IDictionary<string, object>;
            if (element.Elements().Any(e => e.HasElements))
            {
                var list = new List<ExpandoObject>();
                result.Add(element.Name.ToString(), list);
                foreach (var childElement in element.Elements())
                {
                    list.Add(CreateExpando(childElement));
                }
            }
            else
            {
                foreach (var leafElement in element.Elements())
                {
                    result.Add(leafElement.Name.ToString(), leafElement.Value);
                }
            }
            return result;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace DynamicReadXml
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = XDocument.Load("employee.xml");
            var result = doc.AsExpando();
            foreach (var employee in result.Employees)
            {
                Console.WriteLine(employee.FirstName);
            }
            Console.ReadKey();
        }
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <FirstName>DebugLZQ1</FirstName>
  </Employee>
  <Employee>
    <FirstName>DebugLZQ2</FirstName>
  </Employee>
  <Employee>
    <FirstName>DebugLZQ3</FirstName>
  </Employee>
  <Employee>
    <FirstName>DebugLZQ4</FirstName>
  </Employee>
  <Employee>
    <FirstName>DebugLZQ5</FirstName>
  </Employee>
  <Employee>
    <FirstName>DebugLZQ6</FirstName>
  </Employee>
</Employees>

 

.net4 dynamic parse xml

标签:

原文地址:http://www.cnblogs.com/asingna/p/5386164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!