I have been blogging for a while on C# 3.0, DLinq, and now it is time to blog about XLinq. In this post, I will show you how to load an XML file using the new XML namespace: System.Xml.Linq. This sample loads an XML for a menu on a website (under development), then creates a list of all the menu items as a List<MenuItem> collection.
The menu XML file is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSuiteMenu>
<MenuItem>
<Title>Home</Title>
<Href>default.aspx</Href>
</MenuItem>
<MenuItem>
<Title>About us</Title>
<Href>aboutus.aspx</Href>
</MenuItem>
<MenuItem>
<Title>Articles</Title>
<Href>articles.aspx</Href>
</MenuItem>
<MenuItem>
<Title>Resources</Title>
<Href>Training</Href>
</MenuItem>
<MenuItem>
<Title>Training</Title>
<Href>training.aspx</Href>
</MenuItem>
<MenuItem>
<Title>Consulting</Title>
<Href>consulting.aspx</Href>
</MenuItem>
<MenuItem>
<Title>Contact</Title>
<Href>contact.aspx</Href>
</MenuItem>
</CodeSuiteMenu>
The MenuItem.cs class is as follows:
public class MenuItem
{
private string title;
private string href;
public string Title
{
get { return this.title; }
set { this.title = value; }
}
public string Href
{
get { return this.href; }
set { this.href = value; }
}
internal MenuItem()
{ }
public MenuItem(string p_Name, string p_Href)
{
this.title = p_Name;
this.href = p_Href;
}
}
The MenuItem class shall be populated with the items in the XML file.
Now, how to fill the collection of MenuItems from the XML file?
// Query the menu.xml file into an XElement
XElement menuItems= null;
try
{
menuItems = XElement.Load(HttpContext.Current.Server.MapPath("menu.xml"));
}
catch (System.Xml.XmlException ex)
{
throw ex;
}
// Get the MenuItems collection
List<MenuItem> menuItemsCol= new List<MenuItem>();
foreach (XElement x in menuItems.Elements("MenuItem"))
{
CodeSuiteWeb.Menu.MenuItem item =
new CodeSuiteWeb.Menu.MenuItem {Title=(string)x.Element("Title"), Href=(string)x.Element("Href")};
if (item != null)
menuItemsCol.Add(item);
}
As you can see, we use the Load method of the XElement to load an xml file, then in the foreach, we use the Elements method to retrieve the content of the root XElement as an IEnumerable of all the XElements in the xml file. For each XElement, we initialize a new instance of MenuItem using C# 3.0 Object Initialization. If the item created not null, we add it to the collection!
Hope this helps you,
Regards
Tags: XLinq