XElement.Load Method

Definition

Creates a new XElement from a file specified by a URI, from an TextReader, or from an XmlReader.

Overloads

Load(TextReader, LoadOptions)

Loads an XElement from a TextReader, optionally preserving white space and retaining line information.

Load(XmlReader, LoadOptions)

Loads an XElement from an XmlReader, optionally preserving white space, setting the base URI, and retaining line information.

Load(String, LoadOptions)

Loads an XElement from a file, optionally preserving white space, setting the base URI, and retaining line information.

Load(Stream, LoadOptions)

Creates a new XElement instance by using the specified stream, optionally preserving white space, setting the base URI, and retaining line information.

Load(TextReader)

Loads an XElement from a TextReader.

Load(String)

Loads an XElement from a file.

Load(Stream)

Creates a new XElement instance by using the specified stream.

Load(XmlReader)

Loads an XElement from an XmlReader.

Remarks

You can use one of the overloads of this method to load an XElement from a file, a TextReader, or an XmlReader.

To create an XElement from a string that contains XML, use Parse.

Load(TextReader, LoadOptions)

Loads an XElement from a TextReader, optionally preserving white space and retaining line information.

public:
 static System::Xml::Linq::XElement ^ Load(System::IO::TextReader ^ textReader, System::Xml::Linq::LoadOptions options);
public static System.Xml.Linq.XElement Load (System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options);
static member Load : System.IO.TextReader * System.Xml.Linq.LoadOptions -> System.Xml.Linq.XElement
Public Shared Function Load (textReader As TextReader, options As LoadOptions) As XElement

Parameters

textReader
TextReader

A TextReader that will be read for the XElement content.

options
LoadOptions

A LoadOptions that specifies white space behavior, and whether to load base URI and line information.

Returns

An XElement that contains the XML that was read from the specified TextReader.

Examples

The following example loads an XElement from a StringReader in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree.

TextReader sr;
int whiteSpaceNodes;

sr = new StringReader("<Root> <Child> </Child> </Root>");
XElement xmlTree1 = XElement.Load(sr, LoadOptions.None);
sr.Close();
whiteSpaceNodes = xmlTree1
    .DescendantNodesAndSelf()
    .OfType<XText>()
    .Where(tNode => tNode.ToString().Trim().Length == 0)
    .Count();
Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes);

sr = new StringReader("<Root> <Child> </Child> </Root>");
XElement xmlTree2 = XElement.Load(sr, LoadOptions.PreserveWhitespace);
sr.Close();
whiteSpaceNodes = xmlTree2
    .DescendantNodesAndSelf()
    .OfType<XText>()
    .Where(tNode => tNode.ToString().Trim().Length == 0)
    .Count();
Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes);
Dim sr As TextReader
Dim whiteSpaceNodes As Integer

sr = New StringReader("<Root> <Child> </Child> </Root>")
Dim xmlTree1 As XElement = XElement.Load(sr, LoadOptions.None)
sr.Close()
whiteSpaceNodes = xmlTree1 _
    .DescendantNodesAndSelf() _
    .OfType(Of XText)() _
    .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _
    .Count()
Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes)

sr = New StringReader("<Root> <Child> </Child> </Root>")
Dim xmlTree2 As XElement = XElement.Load(sr, LoadOptions.PreserveWhitespace)
sr.Close()
whiteSpaceNodes = xmlTree2 _
    .DescendantNodesAndSelf() _
    .OfType(Of XText)() _
    .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _
    .Count()
Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes)

This example produces the following output:

Count of white space nodes (not preserving whitespace): 0
Count of white space nodes (preserving whitespace): 3

The following example loads the line information as it loads from the TextReader. It then prints the line information.

TextReader sr = new StringReader(
@"<Root>
  <Child>
    <GrandChild1/>
    <GrandChild2/>
  </Child>
</Root>");
XElement po = XElement.Load(sr,
    LoadOptions.SetLineInfo);
Console.WriteLine("{0}{1}{2}",
    "Element Name".PadRight(20),
    "Line".PadRight(5),
    "Position");
Console.WriteLine("{0}{1}{2}",
    "------------".PadRight(20),
    "----".PadRight(5),
    "--------");
foreach (XElement e in po.DescendantsAndSelf())
    Console.WriteLine("{0}{1}{2}",
        ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20),
        ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5),
        ((IXmlLineInfo)e).LinePosition);
Dim sr As TextReader = New StringReader( _
    "<Root>" & Environment.NewLine & _
    "  <Child>" & Environment.NewLine & _
    "    <GrandChild1/>" & Environment.NewLine & _
    "    <GrandChild2/>" & Environment.NewLine & _
    "  </Child>" & Environment.NewLine & _
    "</Root>")
Dim po As XElement = XElement.Load(sr, LoadOptions.SetLineInfo)
Console.WriteLine("{0}{1}{2}", _
    "Element Name".PadRight(20), _
    "Line".PadRight(5), _
    "Position")
Console.WriteLine("{0}{1}{2}", _
    "------------".PadRight(20), _
    "----".PadRight(5), _
    "--------")
For Each e As XElement In po.DescendantsAndSelf()
    Console.WriteLine("{0}{1}{2}", _
        ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _
        (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _
        (DirectCast(e, IXmlLineInfo)).LinePosition)
Next

This example produces the following output:

Element Name        Line Position
------------        ---- --------
Root                1    2
  Child             2    4
    GrandChild1     3    6
    GrandChild2     4    6

Remarks

If the source XML is indented, setting the PreserveWhitespace flag in options causes the reader to read all white space in the source XML. Nodes of type XText are created for both significant and insignificant white space.

If the source XML is indented, not setting the PreserveWhitespace flag in options causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space.

If the source XML is not indented, setting the PreserveWhitespace flag in options has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes.

For more information, see Preserve white space while loading or parsing XML and Preserve white space while serializing.

Use Parse to create an XElement from a string that contains XML.

Setting SetBaseUri will have no effect when loading from a TextReader.

There is a performance penalty if you set the SetLineInfo flag.

The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless.

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

See also

Applies to

Load(XmlReader, LoadOptions)

Loads an XElement from an XmlReader, optionally preserving white space, setting the base URI, and retaining line information.

public:
 static System::Xml::Linq::XElement ^ Load(System::Xml::XmlReader ^ reader, System::Xml::Linq::LoadOptions options);
public static System.Xml.Linq.XElement Load (System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options);
static member Load : System.Xml.XmlReader * System.Xml.Linq.LoadOptions -> System.Xml.Linq.XElement
Public Shared Function Load (reader As XmlReader, options As LoadOptions) As XElement

Parameters

reader
XmlReader

A XmlReader that will be read for the content of the XElement.

options
LoadOptions

A LoadOptions that specifies white space behavior, and whether to load base URI and line information.

Returns

An XElement that contains the XML that was read from the specified XmlReader.

Examples

The following example loads the line information that it loads from the XmlReader. It then prints the line information.

string markup =
@"<Root>
    <Child>
        <GrandChild/>
    </Child>
</Root>";

// Create a reader and move to the content.
using (XmlReader nodeReader = XmlReader.Create(new StringReader(markup)))
{
    // the reader must be in the Interactive state in order to
    // Create a LINQ to XML tree from it.
    nodeReader.MoveToContent();

    XElement xRoot = XElement.Load(nodeReader, LoadOptions.SetLineInfo);
    Console.WriteLine("{0}{1}{2}",
        "Element Name".PadRight(20),
        "Line".PadRight(5),
        "Position");
    Console.WriteLine("{0}{1}{2}",
        "------------".PadRight(20),
        "----".PadRight(5),
        "--------");
    foreach (XElement e in xRoot.DescendantsAndSelf())
        Console.WriteLine("{0}{1}{2}",
            ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20),
            ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5),
            ((IXmlLineInfo)e).LinePosition);
}
Dim markup As String = _
    "<Root>" & Environment.NewLine & _
    "    <Child>" & Environment.NewLine & _
    "        <GrandChild/>" & Environment.NewLine & _
    "    </Child>" & Environment.NewLine & _
    "</Root>"

' Create a reader and move to the content.
Using nodeReader As XmlReader = XmlReader.Create(New StringReader(markup))

    ' the reader must be in the Interactive state in order to
    ' Create a LINQ to XML tree from it.
    nodeReader.MoveToContent()

    Dim xRoot As XElement = XElement.Load(nodeReader, LoadOptions.SetLineInfo)
    Console.WriteLine("{0}{1}{2}", _
        "Element Name".PadRight(20), _
        "Line".PadRight(5), _
        "Position")
    Console.WriteLine("{0}{1}{2}", _
        "------------".PadRight(20), _
        "----".PadRight(5), _
        "--------")
    For Each e As XElement In xRoot.DescendantsAndSelf()
        Console.WriteLine("{0}{1}{2}", _
            ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _
            (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _
            (DirectCast(e, IXmlLineInfo)).LinePosition)
    Next
End Using

This example produces the following output:

Element Name        Line Position
------------        ---- --------
Root                1    2
  Child             2    6
    GrandChild      3    10

Remarks

By creating an XmlNodeReader from a DOM document, and then using the XmlNodeReader to create an XElement, this method can be used to create a copy of a DOM document in a LINQ to XML tree.

Use Parse to create an XElement from a string that contains XML.

Setting PreserveWhitespace is not valid when loading from a XmlReader. The XmlReader will be configured to either read whitespace or not. The LINQ to XML tree will be populated with the whitespace nodes that the reader surfaces. This will be the behavior regardless of whether PreserveWhitespace is set or not.

The XmlReader may have a valid base URI or not. If you set SetBaseUri, the base URI will be set in the XML tree from the base URI that is reported by the XmlReader.

The XmlReader may have a valid line information or not. If you set SetLineInfo, the line information will be set in the XML tree from the line information that is reported by the XmlReader.

There is a performance penalty if you set the SetLineInfo flag.

The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless.

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

See also

Applies to

Load(String, LoadOptions)

Loads an XElement from a file, optionally preserving white space, setting the base URI, and retaining line information.

public:
 static System::Xml::Linq::XElement ^ Load(System::String ^ uri, System::Xml::Linq::LoadOptions options);
public static System.Xml.Linq.XElement Load (string uri, System.Xml.Linq.LoadOptions options);
static member Load : string * System.Xml.Linq.LoadOptions -> System.Xml.Linq.XElement
Public Shared Function Load (uri As String, options As LoadOptions) As XElement

Parameters

uri
String

A URI string referencing the file to load into an XElement.

options
LoadOptions

A LoadOptions that specifies white space behavior, and whether to load base URI and line information.

Returns

An XElement that contains the contents of the specified file.

Examples

The following example loads an XElement from a file in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree.

XElement xmlTree1 = XElement.Parse("<Root> <Child>  </Child> </Root>", LoadOptions.PreserveWhitespace);
xmlTree1.Save("Tree.xml");
Console.WriteLine(xmlTree1);

int whiteSpaceNodes;
XElement xmlTree2 = XElement.Load("Tree.xml",
    LoadOptions.None);
whiteSpaceNodes = xmlTree2
    .DescendantNodesAndSelf()
    .OfType<XText>()
    .Where(tNode => tNode.ToString().Trim().Length == 0)
    .Count();
Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes);

XElement xmlTree3 = XElement.Load("Tree.xml",
    LoadOptions.PreserveWhitespace);
whiteSpaceNodes = xmlTree3
    .DescendantNodesAndSelf()
    .OfType<XText>()
    .Where(tNode => tNode.ToString().Trim().Length == 0)
    .Count();
Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes);
Dim xmlTree1 As XElement = XElement.Parse("<Root> <Child>  </Child> </Root>", LoadOptions.PreserveWhitespace)
xmlTree1.Save("Tree.xml")
Console.WriteLine(xmlTree1)

Dim whiteSpaceNodes As Integer
Dim xmlTree2 As XElement = XElement.Load("Tree.xml", LoadOptions.None)
whiteSpaceNodes = xmlTree2 _
                  .DescendantNodesAndSelf() _
                  .OfType(Of XText)() _
                  .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _
                  .Count()
Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes)

Dim xmlTree3 As XElement = XElement.Load("Tree.xml", LoadOptions.PreserveWhitespace)
whiteSpaceNodes = xmlTree3 _
                  .DescendantNodesAndSelf() _
                  .OfType(Of XText)() _
                  .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _
                  .Count()
Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes)

This example produces the following output:

<Root> <Child>  </Child> </Root>
Count of white space nodes (not preserving whitespace): 0
Count of white space nodes (preserving whitespace): 3

The following example loads the base URI and line information as it loads the file. It then prints the base URI and the line information.

This example uses the following resource file: Sample XML File: Typical Purchase Order (LINQ to XML).

XElement po = XElement.Load("PurchaseOrder.xml",
    LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
string[] splitUri = po.BaseUri.Split('/');
Console.WriteLine("BaseUri: {0}", splitUri[splitUri.Length - 1]);
Console.WriteLine();
Console.WriteLine("{0}{1}{2}",
    "Element Name".PadRight(20),
    "Line".PadRight(5),
    "Position");
Console.WriteLine("{0}{1}{2}",
    "------------".PadRight(20),
    "----".PadRight(5),
    "--------");
foreach (XElement e in po.DescendantsAndSelf())
    Console.WriteLine("{0}{1}{2}",
        ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20),
        ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5),
        ((IXmlLineInfo)e).LinePosition);
Dim po As XElement = XElement.Load("PurchaseOrder.xml", LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo)
Dim splitUri() As String = po.BaseUri.Split("/")
Console.WriteLine("BaseUri: {0}", splitUri(splitUri.Length - 1))
Console.WriteLine()
Console.WriteLine("{0}{1}{2}", _
    "Element Name".PadRight(20), _
    "Line".PadRight(5), _
    "Position")
Console.WriteLine("{0}{1}{2}", _
    "------------".PadRight(20), _
    "----".PadRight(5), _
    "--------")
For Each e As XElement In po.DescendantsAndSelf()
    Console.WriteLine("{0}{1}{2}", _
        ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString()).PadRight(20), _
        (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _
        (DirectCast(e, IXmlLineInfo)).LinePosition)
Next

This example produces the following output:

BaseUri: PurchaseOrder.xml

Element Name        Line Position
------------        ---- --------
PurchaseOrder       2    2
  Address           3    4
    Name            4    6
    Street          5    6
    City            6    6
    State           7    6
    Zip             8    6
    Country         9    6
  Address           11   4
    Name            12   6
    Street          13   6
    City            14   6
    State           15   6
    Zip             16   6
    Country         17   6
  DeliveryNotes     19   4
  Items             20   4
    Item            21   6
      ProductName   22   8
      Quantity      23   8
      USPrice       24   8
      Comment       25   8
    Item            27   6
      ProductName   28   8
      Quantity      29   8
      USPrice       30   8
      ShipDate      31   8

Remarks

If the source XML is indented, setting the PreserveWhitespace flag in options causes the reader to read all white space in the source XML. Nodes of type XText are created for both significant and insignificant white space.

If the source XML is indented, not setting the PreserveWhitespace flag in options causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space.

If the source XML is not indented, setting the PreserveWhitespace flag in options has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes.

For more information, see Preserve white space while loading or parsing XML and Preserve white space while serializing.

Use Parse to create an XElement from a string that contains XML.

There is a performance penalty if you set the SetBaseUri and the SetLineInfo flags.

The base URI and the line information are accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the base URI and line information may become meaningless.

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

See also

Applies to

Load(Stream, LoadOptions)

Creates a new XElement instance by using the specified stream, optionally preserving white space, setting the base URI, and retaining line information.

public:
 static System::Xml::Linq::XElement ^ Load(System::IO::Stream ^ stream, System::Xml::Linq::LoadOptions options);
public static System.Xml.Linq.XElement Load (System.IO.Stream stream, System.Xml.Linq.LoadOptions options);
static member Load : System.IO.Stream * System.Xml.Linq.LoadOptions -> System.Xml.Linq.XElement
Public Shared Function Load (stream As Stream, options As LoadOptions) As XElement

Parameters

stream
Stream

The stream containing the XML data.

options
LoadOptions

A LoadOptions object that specifies whether to load base URI and line information.

Returns

An XElement object used to read the data that the stream contains.

Remarks

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

If you have to modify XmlReaderSettings, following these steps:

  1. Create an XmlReader by calling one of the Create overloads that take XmlReaderSettings as a parameter.

  2. Pass the XmlReader to one of the XElement's Load overloads that takes XmlReader as a parameter.

Applies to

Load(TextReader)

Loads an XElement from a TextReader.

public:
 static System::Xml::Linq::XElement ^ Load(System::IO::TextReader ^ textReader);
public static System.Xml.Linq.XElement Load (System.IO.TextReader textReader);
static member Load : System.IO.TextReader -> System.Xml.Linq.XElement
Public Shared Function Load (textReader As TextReader) As XElement

Parameters

textReader
TextReader

A TextReader that will be read for the XElement content.

Returns

An XElement that contains the XML that was read from the specified TextReader.

Examples

The following example loads an element from a StringReader.

TextReader sr = new StringReader("<Root><Child/></Root>");
XElement xmlTree = XElement.Load(sr);
sr.Close();
Console.WriteLine(xmlTree);
Dim sr As TextReader = New StringReader("<Root><Child/></Root>")
Dim xmlTree As XElement = XElement.Load(sr)
sr.Close()
Console.WriteLine(xmlTree)

This example produces the following output:

<Root>
  <Child />
</Root>

Remarks

This method reads the raw XML into the XML tree. It discards all insignificant white space in the file.

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

See also

Applies to

Load(String)

Loads an XElement from a file.

public:
 static System::Xml::Linq::XElement ^ Load(System::String ^ uri);
public static System.Xml.Linq.XElement Load (string uri);
static member Load : string -> System.Xml.Linq.XElement
Public Shared Function Load (uri As String) As XElement

Parameters

uri
String

A URI string referencing the file to load into a new XElement.

Returns

An XElement that contains the contents of the specified file.

Examples

The following example creates an XML tree, saves it to a file, and then uses this method to load the XElement from the file.

XElement xmlTree1 = new XElement("Root",
    new XElement("Child", "content")
);
xmlTree1.Save("Tree.xml");

XElement xmlTree2 = XElement.Load("Tree.xml");
Console.WriteLine(xmlTree2.Name);
Dim xmlTree1 As XElement = _
        <Root>
            <Child>Content</Child>
        </Root>
xmlTree1.Save("Tree.xml")

Dim xmlTree2 As XElement = XElement.Load("Tree.xml")
Console.WriteLine(xmlTree2.Name)

This example produces the following output:

Root

Remarks

This method reads the raw XML into the XML tree. It discards all insignificant white space in the file.

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

See also

Applies to

Load(Stream)

Creates a new XElement instance by using the specified stream.

public:
 static System::Xml::Linq::XElement ^ Load(System::IO::Stream ^ stream);
public static System.Xml.Linq.XElement Load (System.IO.Stream stream);
static member Load : System.IO.Stream -> System.Xml.Linq.XElement
Public Shared Function Load (stream As Stream) As XElement

Parameters

stream
Stream

The stream that contains the XML data.

Returns

An XElement object used to read the data that is contained in the stream.

Remarks

If you want to control load options, use the Load overload that takes LoadOptions as a parameter.

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

If you have to modify XmlReaderSettings, following these steps:

  1. Create an XmlReader by calling one of the Create overloads that take XmlReaderSettings as a parameter.

  2. Pass the XmlReader to one of the XElement's Load overloads that takes XmlReader as a parameter.

Applies to

Load(XmlReader)

Loads an XElement from an XmlReader.

public:
 static System::Xml::Linq::XElement ^ Load(System::Xml::XmlReader ^ reader);
public static System.Xml.Linq.XElement Load (System.Xml.XmlReader reader);
static member Load : System.Xml.XmlReader -> System.Xml.Linq.XElement
Public Shared Function Load (reader As XmlReader) As XElement

Parameters

reader
XmlReader

A XmlReader that will be read for the content of the XElement.

Returns

An XElement that contains the XML that was read from the specified XmlReader.

Examples

The following example creates a DOM document, creates an XmlNodeReader from the DOM document, instantiates a tree from the reader. This code effectively copies a DOM document into a LINQ to XML tree.

// Create a DOM document with some content.
XmlDocument doc = new XmlDocument();
XmlElement child = doc.CreateElement("Child");
child.InnerText = "child contents";
XmlElement root = doc.CreateElement("Root");
root.AppendChild(child);
doc.AppendChild(root);

// Create a reader and move to the content.
using (XmlNodeReader nodeReader = new XmlNodeReader(doc)) {
    // the reader must be in the Interactive state in order to
    // Create a LINQ to XML tree from it.
    nodeReader.MoveToContent();

    XElement xRoot = XElement.Load(nodeReader);
    Console.WriteLine(xRoot);
}
' Create a DOM document with some content.
Dim doc As XmlDocument = New XmlDocument()
Dim child As XmlElement = doc.CreateElement("Child")
child.InnerText = "child contents"
Dim root As XmlElement = doc.CreateElement("Root")
root.AppendChild(child)
doc.AppendChild(root)

' Create a reader and move to the content.
Using nodeReader = New XmlNodeReader(doc)
    ' the reader must be in the Interactive state in order to
    ' Create a LINQ to XML tree from it.
    nodeReader.MoveToContent()

    Dim xRoot As XElement = XElement.Load(nodeReader)
    Console.WriteLine(xRoot)
End Using

This example produces the following output:

<Root>
  <Child>child contents</Child>
</Root>

Remarks

By creating an XmlNodeReader from a DOM document, and then using the XmlNodeReader to create an XElement, this method can be used to create a copy of a DOM document in a LINQ to XML tree.

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

See also

Applies to