C# XElement

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.

LINQ

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.

Page

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.

Program that uses XElement.Load on sitemap: C#

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);
	    Console.WriteLine(locElement.Value);
	}

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

End of sample XML file: sitemap.xml

<url>
<loc>http://www.dotnetperls.com/xor</loc>
<image:image><image:loc>http://www.dotnetperls.com/xor.png</image:loc></image:image>
</url>

<url>
<loc>http://www.dotnetperls.com/yield</loc>
<image:image><image:loc>http://www.dotnetperls.com/yield.png</image:loc></image:image>
</url>

<url>
<loc>http://www.dotnetperls.com/zip</loc>
</url>
</urlset>

End of output

http://www.dotnetperls.com/xor
http://www.dotnetperls.com/yield
http://www.dotnetperls.com/zip
Count: 1247
Note

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.

CountIEnumerable Examples: LINQ, Lists and Arrays

Example 2

Continuing on, we look at how you can 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);
    }
}
Squares

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.

MapPathStatic Method

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.

Singleton Class

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

XML

Extensible markup language: 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"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SitePage>
    <Visibility>Supplementary</Visibility>
    <Title>C# .NET Examples and Resources</Title>
    <Url></Url>
    <Category>None</Category>
  </SitePage>
  <SitePage>
    <Visibility>Supplementary</Visibility>
    <Title>Usability Guidelines for Web Writing</Title>
    <Url>Content/Usability-Writing.aspx</Url>
    <Category>None</Category>
  </SitePage>
  <SitePage>
    <Visibility>Regular</Visibility>
    <Title>Alphanumeric Sorting in C#</Title>
    <Url>Content/Alphanumeric-Sorting.aspx</Url>
    <Category>Algorithms</Category>
  </SitePage>
  <SitePage>
    <Visibility>Regular</Visibility>
    <Title>Word Count Algorithm in C#</Title>
    <Url>Content/Word-Count-Algorithm.aspx</Url>
    <Category>Algorithms</Category>
  </SitePage>
</ArrayOfSitePage>

Summary

LINQ: language integrated query

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.


C#: File: XML