Home
C#
XElement Example
This page was last reviewed on Jun 28, 2021.
Dot Net Perls
XElement. This C# class loads and parses XML. It allows you to eliminate the possibility of bugs and other small mistakes. It is part of the LINQ extensions in System.Xml.Linq.
Intro notes. We can use XElement to load (and query) an XML document. Less custom code is required with XElement, although performance will suffer compared to lower-level solutions.
Sitemap file. To begin, save this file in known location on your disk. Then update the path (used in XElement.Load) in the C# program to point to the file.
<urlset> <url> <loc>http://www.dotnetperls.com/xor</loc> </url> <url> <loc>http://www.dotnetperls.com/yield</loc> </url> <url> <loc>http://www.dotnetperls.com/zip</loc> </url> </urlset>
Example code. This example loads a sitemap XML file. A sitemap contains a list of all pages and (in some cases) images. The XElement type can access a local or remote file.
Detail We create 2 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.
Detail We call the Elements() method with the XName argument. This returns all "url" elements in the sitemap.
Info The program calls the Count() extension method to count all the Elements(). This is needed on an IEnumerable.
Count
IEnumerable
using System; using System.Linq; using System.Xml.Linq; class Program { static void Main() { // Open XML file. XElement sitemap = XElement.Load("/Users/sam/file.xml"); XName url = XName.Get("url"); XName loc = XName.Get("loc"); // 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()); } }
http://www.dotnetperls.com/xor http://www.dotnetperls.com/yield http://www.dotnetperls.com/zip Count: 3
An update. This page has been updated for .NET 6 Preview 5 in 2021 to work correctly. It relied on an external XML file that was removed.
A summary. We used XElement and its Load() method to consume XML. Code can load an XML file in a single statement and then run queries on it to generate output.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 28, 2021 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.