CSharp - XML Loading with XDocument.Load()

Introduction

You can load your XML document using any of several methods. Here is a list:

static XDocument XDocument.Load(string uri);
static XDocument XDocument.Load(TextReader textReader);
static XDocument XDocument.Load(XmlReader reader);
static XDocument XDocument.Load(string uri, LoadOptions options);
static XDocument XDocument.Load(TextReader textReader, LoadOptions options);
static XDocument XDocument.Load(XmlReader reader, LoadOptions options);

The Load method is static.

The LoadOptions enum has the options shown in the following table.

Option
Description
LoadOptions.None
Use this option to specify that no load options are to be used.
LoadOptions.PreserveWhitespace

Use this option to preserve the whitespace in the XML source,
such as blank lines.
LoadOptions.SetLineInfo


Use this option so that you may obtain the line and position of
any object inheriting from XObject by using the IXmlLineInfo
interface.
LoadOptions.SetBaseUri

Use this option so that you may obtain the base URI of any
object inheriting from XObject.

Demo

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

class Program/*from   w  ww.j a  v a2  s.c  o m*/
{
    static void Main(string[] args)
    {
        XDocument xDocument = XDocument.Load("bookparticipants.xml",
          LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);

        Console.WriteLine(xDocument);

        XElement firstName = xDocument.Descendants("FirstName").First();

        Console.WriteLine("FirstName Line:{0} - Position:{1}",
          ((IXmlLineInfo)firstName).LineNumber,
          ((IXmlLineInfo)firstName).LinePosition);

        Console.WriteLine("FirstName Base URI:{0}", firstName.BaseUri);
    }
}

Result

Related Topics