0
点赞
收藏
分享

微信扫一扫

[代码]使用XmlReader对XML片段进行流式处理(LINQ to XML)


本代码主要演示如何使用XmlReader对XML片段进行流式处理。这种做法,对大型的XML文档特别有用,它所需要的内存量非常的小。

示例代码在示例代码中,定义了一个自定义轴方法。在此轴方法中,通过调用XElement.ReadFrom()方法创建XML片段后,然后使用yield return返回该集合。这种做法可为自定义轴方法提供延迟执行语义。此自定义轴方法会查找出XML中的元素名为Child的所有元素。
然后在LINQ to XML的查询中将自定义轴方法的结果作为数据源,检索出Child元素的Key属性值大于1的所有的Child元素的GrandChild子元素的值,并将其打印到控制台上。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.IO;

namespace Demo06Ex01
{
    class Program
    {
        static IEnumerable<XElement> StreamRootChildDoc(StringReader SReader)
        {
            using (XmlReader Reader = XmlReader.Create(SReader))
            {
                Reader.MoveToContent();
                while (Reader.Read())
                {
                    switch (Reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            if (Reader.Name == "Child")
                            {
                                XElement ChildElement = XElement.ReadFrom(Reader) as XElement;
                                if (ChildElement != null)
                                    yield return ChildElement;
                            }
                            break;
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            string XmlContent = @"<Root>
              <Child Key=""01"">
                <GrandChild>aaa</GrandChild>
              </Child>
              <Child Key=""02"">
                <GrandChild>bbb</GrandChild>
              </Child>
              <Child Key=""03"">
                <GrandChild>ccc</GrandChild>
              </Child>
            </Root>";

            var GrandChildValues =
                from Element in StreamRootChildDoc(new StringReader(XmlContent))
                where (int)Element.Attribute("Key") > 1
                select Element.Element("GrandChild").Value;

            foreach (var GrandChildValue in GrandChildValues)
            {
                Console.WriteLine(GrandChildValue);
            }
        }
    }
}

举报

相关推荐

0 条评论