Editar

Compartilhar via


XDocument.Load Method

Definition

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

Overloads

Load(Stream)

Creates a new XDocument instance by using the specified stream.

Load(TextReader)

Creates a new XDocument from a TextReader.

Load(String)

Creates a new XDocument from a file.

Load(XmlReader)

Creates a new XDocument from an XmlReader.

Load(Stream, LoadOptions)

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

Load(TextReader, LoadOptions)

Creates a new XDocument from a TextReader, optionally preserving white space, setting the base URI, and retaining line information.

Load(String, LoadOptions)

Creates a new XDocument from a file, optionally preserving white space, setting the base URI, and retaining line information.

Load(XmlReader, LoadOptions)

Loads an XDocument from an XmlReader, optionally setting the base URI, and retaining line information.

Remarks

Using one of the overloads of this method, you can load an XDocument from a file, a TextReader, or an XmlReader.

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

Load(Stream)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

Creates a new XDocument instance by using the specified stream.

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

Parameters

stream
Stream

The stream that contains the XML data.

Returns

An XDocument object that reads 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.

The loading functionality of LINQ to XML 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, follow 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 Load overloads of XDocument that takes XmlReader as a parameter.

Applies to

Load(TextReader)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

Creates a new XDocument from a TextReader.

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

Parameters

textReader
TextReader

A TextReader that contains the content for the XDocument.

Returns

An XDocument that contains the contents of the specified TextReader.

Examples

The following example creates a document from a StringReader.

TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);
Dim tr As TextReader = New StringReader("<Root>Content</Root>")
Dim doc As XDocument = XDocument.Load(tr)
Console.WriteLine(doc)

This example produces the following output:

<Root>Content</Root>

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.

See also

Applies to

Load(String)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

Creates a new XDocument from a file.

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

Parameters

uri
String

A URI string that references the file to load into a new XDocument.

Returns

An XDocument that contains the contents of the specified file.

Examples

The following example shows how to load an XDocument from a file.

This example uses the following XML document:

Sample XML File: Typical Purchase Order (LINQ to XML)

XDocument doc = XDocument.Load("PurchaseOrder.xml");
Console.WriteLine(doc);
Dim doc As XDocument = XDocument.Load("PurchaseOrder.xml")
Console.WriteLine(doc)

This example produces the following output:

<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
  <Address Type="Shipping">
    <Name>Ellen Adams</Name>
    <Street>123 Maple Street</Street>
    <City>Mill Valley</City>
    <State>CA</State>
    <Zip>10999</Zip>
    <Country>USA</Country>
  </Address>
  <Address Type="Billing">
    <Name>Tai Yee</Name>
    <Street>8 Oak Avenue</Street>
    <City>Old Town</City>
    <State>PA</State>
    <Zip>95819</Zip>
    <Country>USA</Country>
  </Address>
  <DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>
  <Items>
    <Item PartNumber="872-AA">
      <ProductName>Lawnmower</ProductName>
      <Quantity>1</Quantity>
      <USPrice>148.95</USPrice>
      <Comment>Confirm this is electric</Comment>
    </Item>
    <Item PartNumber="926-AA">
      <ProductName>Baby Monitor</ProductName>
      <Quantity>2</Quantity>
      <USPrice>39.98</USPrice>
      <ShipDate>1999-05-21</ShipDate>
    </Item>
  </Items>
</PurchaseOrder>

Remarks

This method uses an underlying XmlReader to read the XML into an XML tree.

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

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)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

Creates a new XDocument from an XmlReader.

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

Parameters

reader
XmlReader

A XmlReader that contains the content for the XDocument.

Returns

An XDocument that contains the contents of the specified XmlReader.

Examples

The following example creates a DOM document, creates an XmlNodeReader from the DOM document, creates an XDocument using the XmlNodeReader.

// 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();

    XDocument xRoot = XDocument.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 XDocument = XDocument.Load(nodeReader)
    Console.WriteLine(xRoot)
End Using

This example produces the following output:

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

Remarks

One possible use for this method is to create a copy of a DOM document in a LINQ to XML tree. To do this, you create an XmlNodeReader from a DOM document, and then use the XmlNodeReader to create an XDocument.

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)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

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

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

Parameters

stream
Stream

The stream containing the XML data.

options
LoadOptions

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

Returns

An XDocument object that reads the data that is contained in the stream.

Remarks

The loading functionality of LINQ to XML 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, follow these steps:

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

  2. Pass the XmlReader to one of the Load overloads of XDocument that takes XmlReader as a parameter.

Applies to

Load(TextReader, LoadOptions)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

Creates a new XDocument from a TextReader, optionally preserving white space, setting the base URI, and retaining line information.

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

Parameters

textReader
TextReader

A TextReader that contains the content for the XDocument.

options
LoadOptions

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

Returns

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

Examples

The following example creates a document from a StringReader.

TextReader sr;
int whiteSpaceNodes;

sr = new StringReader("<Root> <Child> </Child> </Root>");
XDocument xmlTree1 = XDocument.Load(sr, LoadOptions.None);
sr.Close();
whiteSpaceNodes = xmlTree1
    .Element("Root")
    .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>");
XDocument xmlTree2 = XDocument.Load(sr, LoadOptions.PreserveWhitespace);
sr.Close();
whiteSpaceNodes = xmlTree2
    .Element("Root")
    .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 XDocument = XDocument.Load(sr, LoadOptions.None)
sr.Close()
whiteSpaceNodes = xmlTree1 _
              .Element("Root") _
              .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 XDocument = XDocument.Load(sr, LoadOptions.PreserveWhitespace)
sr.Close()
whiteSpaceNodes = xmlTree2 _
              .Element("Root") _
              .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

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 is not valid 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(String, LoadOptions)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

Creates a new XDocument from a file, optionally preserving white space, setting the base URI, and retaining line information.

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

Parameters

uri
String

A URI string that references the file to load into a new XDocument.

options
LoadOptions

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

Returns

An XDocument that contains the contents of the specified file.

Examples

The following example shows how to load an XDocument from a file.

This example uses the following XML document:

Sample XML File: Typical Purchase Order (LINQ to XML)

XDocument doc1 = XDocument.Load("PurchaseOrder.xml", LoadOptions.None);
Console.WriteLine("nodes if not preserving whitespace: {0}", doc1.DescendantNodes().Count());

XDocument doc2 = XDocument.Load("PurchaseOrder.xml", LoadOptions.PreserveWhitespace);
Console.WriteLine("nodes if preserving whitespace: {0}", doc2.DescendantNodes().Count());
Dim doc1 As XDocument = XDocument.Load("PurchaseOrder.xml", LoadOptions.None)
Console.WriteLine("nodes if not preserving whitespace: {0}", doc1.DescendantNodes().Count())

Dim doc2 As XDocument = XDocument.Load("PurchaseOrder.xml", LoadOptions.PreserveWhitespace)
Console.WriteLine("nodes if preserving whitespace: {0}", doc2.DescendantNodes().Count())

This example produces the following output:

nodes if not preserving whitespace: 48
nodes if preserving whitespace: 82

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 XDocument 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(XmlReader, LoadOptions)

Source:
XDocument.cs
Source:
XDocument.cs
Source:
XDocument.cs

Loads an XDocument from an XmlReader, optionally setting the base URI, and retaining line information.

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

Parameters

reader
XmlReader

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

options
LoadOptions

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

Returns

An XDocument 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();

    XDocument xRoot = XDocument.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.Elements("Root").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 XDocument = XDocument.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.Elements("Root").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 XDocument 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