Home
Search
C# XElement ExampleUse the XElement type to load an XML file into memory. Invoke XElement.Load and Elements.
dot net perls
XElement loads and parses XML. It allows you to 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.
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 show a sitemap.
XName 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.
Elements 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
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); 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
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.
MapPath MapPath translates from a virtual path to a real server path. This means you can easily open an XML file by its name.
Load XElement.Load reads in the data. This is a static method that allows you to load the XML into memory.
Static
So At this point, the whole XML file is now parsed and resident in memory. No further file system or network accesses are needed.
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); } }
Notes, App_Data. App_Data 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.
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. 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. 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.
Home
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.