How to: Create a Tree from an XmlReader
This topic shows how to create an XML tree directly from an XmlReader. To create an XElement from an XmlReader, you must position the XmlReader on an element node. The XmlReader will skip comments and processing instructions, but if the XmlReader is positioned on a text node, an error will be thrown. To avoid such errors, always position the XmlReader on an element before you create an XML tree from the XmlReader.
Example
This example uses the following XML document: Sample XML File: Books (LINQ to XML).
The following code creates an T:System.Xml.XmlReader object, and then reads nodes until it finds the first element node. It then loads the XElement object.
XmlReader r = XmlReader.Create("books.xml");
while (r.NodeType != XmlNodeType.Element)
r.Read();
XElement e = XElement.Load(r);
Console.WriteLine(e);
Dim r As XmlReader = XmlReader.Create("books.xml")
Do While r.NodeType <> XmlNodeType.Element
r.Read()
Loop
Dim e As XElement = XElement.Load(r)
Console.WriteLine(e)
This example produces the following output:
<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>