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
.
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.
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>
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.
XName
objects. These store both the namespace and the local element name.XName
objects instead of strings to look up elements in XElement
objects.Elements()
method with the XName
argument. This returns all "url" elements in the sitemap.Count()
extension method to count all the Elements()
. This is needed on an 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
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.
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.