0
点赞
收藏
分享

微信扫一扫

[代码]如何从XmlReader创建XML树(LINQ to XML)


此代码演示如何直接从XmlReader创建XML树。

示例代码下面的代码首先使用XmlReader.Create()静态方法创建了一个XmlReader对象。然后将此XmlReader对象作为XElement.Load()方法的参数,这样便可以直接从XmlReader创建树了。需要强调的是,必须确保XmlReader被定为到元素上,否则可能会引发错误。代码中有具体的实现办法。

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

namespace Demo05Ex01
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlReader Reader = XmlReader.Create(@"C:/LINQ/Books.xml");
            while (Reader.NodeType != XmlNodeType.Element)
                Reader.Read();

            XElement Books = XElement.Load(Reader);
            Console.WriteLine(Books);
        }
    }
}


上面程序打印到控制台上XML内容如下:

<Catalog>
  <Book id="bk101">
    <Author>Garghentini, Davide</Author>
    <Title>XML Developer's Guide</Title>
    <Genre>Computer</Genre>
    <Price>44.95</Price>
    <PublishDate>2000-10-01</PublishDate>
    <Description>
      An in-depth look at creating applications
      with XML.
    </Description>
  </Book>
  <Book id="bk102">
    <Author>Garcia, Debra</Author>
    <Title>Midnight Rain</Title>
    <Genre>Fantasy</Genre>
    <Price>5.95</Price>
    <PublishDate>2000-12-16</PublishDate>
    <Description>
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    </Description>
  </Book>
</Catalog>

举报

相关推荐

0 条评论