.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda LINQ Parse Path Process Property Regex Replace Sort Split Static StringBuilder Substring Switch Tuple

Letter X

XElement loads and parses XML. It allows you to remove lots of old code and eliminate the possibility of bugs and typos. Here we see an example of XElement from LINQ. We use it to load, and query, an XML document.

Example. This first example loads a sitemap XML file from a website. A sitemap contains a list of all pages and (in some cases) images. The XElement type can access a remote file. For this example we use the present website's sitemap.


XName: We create two XName objects. These store both the namespace and the local element name.

Note: For XML files in a custom namespace, use XName objects instead of strings to look up elements in XElement objects.

We call the Elements() method with the XName argument. This returns all url elements in the sitemap. Then in each url element we print the value of the loc element. We use a separate XName for the loc element.

C# program that uses XElement.Load on sitemap

using System;
using System.Linq;
using System.Xml.Linq;

class Program
    static void Main()
	// ... Download sitemap.
	XElement sitemap = XElement.Load("http://www.dotnetperls.com/sitemap.xml");

	// ... XNames.
	XName url = XName.Get("url", "http://www.sitemaps.org/schemas/sitemap/0.9");
	XName loc = XName.Get("loc", "http://www.sitemaps.org/schemas/sitemap/0.9");

	// ... Loop over url elements.
	// ... Then access each loc element.
	foreach (var urlElement in sitemap.Elements(url))
	    var locElement = urlElement.Element(loc);

	// ... Display count.
	Console.WriteLine("Count: {0}", sitemap.Elements(url).Count());

End of sample XML file: sitemap.xml




End of output

Count: 1247

We can see that the sitemap contains 1247 url elements. Please disregard the image tags within the sitemap.xml. These are not read by the example program. The program successfully extracts the pages from the sitemap.

Note: If you run this program, the output depends on the current state of the sitemap file. If the file was moved, the program will fail.

Also: The program calls the Count() extension method to count all the Elements(). This is needed on an IEnumerable.


Example 2. Continuing on, we use the static Load method on an XML document with XElement. The XElement and XDocument types make using XML easy. To load an XML document into memory you only need one line of code.

Then: You can use methods on the XElement, such as Element() and Elements(), to access the XML elements.

Class that uses XElement: C#

using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Xml.Linq;

public sealed class SiteStructure
    static readonly SiteStructure _instance = new SiteStructure();
    public static SiteStructure Instance
	get { return _instance; }

    XElement _x;

    private SiteStructure()
	string mapLoc = HttpContext.Current.Request.MapPath("~/App_Data/Map1.xml");
	_x = XElement.Load(mapLoc);

MapPath translates from a virtual path to a real server path. This means you can easily open an XML file by its name. XElement.Load reads in the data. This is a static method that allows you to load the XML into memory.


So: At this point, the whole XML file is now parsed and resident in memory. No further file system or network accesses are needed.

The App_Data folder is a special ASP.NET folder for database files or XML files. You could have an XML file in your App_Data folder. Look at the App_Code folder and then add a new C# class. You could make the class a singleton.

LINQ: keywords

Query XML. Next, we query the XML that was loaded with XElement. We are using the XML like a database, but it is entirely in-memory. The queries are native. Look at how the query expressions are used in this example.

Method that uses XElement: C#

public void Example()
    // Get pages matching the title specified.
    string t = "Some title";
    var v = from page in _x.Elements("SitePage")
	    where t == page.Element("Title").Value
	    select page;

    // Get category of first page matched.
    string c = v.First().Element("Category").Value;

    // Count number of elements with that category element value.
    int count = (from p in _x.Elements("SitePage")
		 where p.Element("Category").Value == c &&
		 p.Element("Visibility").Value == "Regular"
		 select p).Count();

Extensible markup language: XML

XML. This is the XML used for this article. You can match up the strings used in the above code samples with the tag and attribute names. This part is completely application-specific—your XML will be different.

However: You can use some of the code samples in this article to help you deal with your XML.

File used: XML

<?xml version="1.0"?>
<ArrayOfSitePage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <Title>C# .NET Examples and Resources</Title>
    <Title>Usability Guidelines for Web Writing</Title>
    <Title>Alphanumeric Sorting in C#</Title>
    <Title>Word Count Algorithm in C#</Title>

LINQ: language integrated query

Summary. We used XElement and its Load method to quickly and effortlessly load XML. Load your XML file in a single statement and then run queries on it to generate output. Improvements could store more detailed data or be modified at runtime.