Export (0) Print
Expand All

XElement.Load Method (String, LoadOptions)

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

Namespace:  System.Xml.Linq
Assembly:  System.Xml.Linq (in System.Xml.Linq.dll)

public static XElement Load(
	string uri,
	LoadOptions options
)

Parameters

uri
Type: System.String
A URI string referencing the file to load into an XElement.
options
Type: System.Xml.Linq.LoadOptions
A LoadOptions that specifies white space behavior, and whether to load base URI and line information.

Return Value

Type: System.Xml.Linq.XElement
An XElement that contains the contents of the specified file.

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 Preserving White Space while Loading or Parsing XML and Preserving 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.

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

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

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

.NET Framework

Supported in: 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

ADD
Show:
© 2014 Microsoft