Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created October 18, 2012 09:49
Show Gist options
  • Save hanssens/3910786 to your computer and use it in GitHub Desktop.
Save hanssens/3910786 to your computer and use it in GitHub Desktop.
[C#] XML SiteMapReader
<?xml version="1.0" encoding="utf-8" ?>
<XmlSiteMap>
<Menu id="home" controller="Home" action="index" title="Mijn Homepage" url="http://mijnhomepage.nl" />
<Menu id="producten" controller="Products" action="overview" title="Mijn Producten" url="http://mijnhomepage/producten/" />
</XmlSiteMap>
/// <summary>
/// Simple proof-of-concept demo for reading a Sitemap.xml file.
/// </summary>
public class SitemapReader : IDisposable
{
private string Filename { get; set; }
public List<SitemapItem> Nodes { get; private set; }
public SitemapReader(string filename)
{
this.Nodes = new List<SitemapItem>();
this.Filename = filename;
Initialize();
}
private void Initialize()
{
XDocument document = null;
using (var stream = new StreamReader(Filename))
{
document = XDocument.Load(stream);
}
var root = document.Element("XmlSiteMap").Elements("Menu");
foreach (var element in root)
{
// Parse the <Menu>-item into the
if (element.HasAttributes)
{
// TODO: Element attribute ID should be case-insensitve
var node = new SitemapItem() {
Id = element.Attribute("id").Value ?? string.Empty,
Title = element.Attribute("title").Value ?? string.Empty,
Action = element.Attribute("action").Value ?? string.Empty ,
Controller = element.Attribute("controller").Value ?? string.Empty ,
ExternalUrl = element.Attribute("url").Value ?? string.Empty
};
Nodes.Add(node);
}
}
}
public void Dispose()
{
this.Nodes.Clear();
}
}
public class SitemapItem
{
public string Id { get; set; }
public string Title { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string ExternalUrl { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment