Search code examples
c#linq-to-xmlweb.sitemap

Could not read web.sitemap


I have been trying reading web.sitemap using LINQ but could not make it. Following is my web.sitemap

<?xml version="1.0" encoding="utf-8"?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode url="" title="Root">
<siteMapNode url="" title="Manage">
  <siteMapNode url="~/Users.aspx" title="Users" name="10001"/>
  <siteMapNode url="~/Targets.aspx" title="Target" name="10002" />
  <siteMapNode url="~/Cases.aspx" title="Case" name="10003" />
  <siteMapNode url="~/GeoFence.aspx" title="Geofence" name= "10004" />
</siteMapNode>
<siteMapNode url="" title="Configure">
  <siteMapNode url="~/CellDirectory.aspx" title="Cell Directory" name="10005" />
  <siteMapNode url="~/WhiteList.aspx" title="White List"  name="10006"/>
  <siteMapNode url="" title="Options" />
</siteMapNode>
<siteMapNode url="" title="Locate">
  <siteMapNode url="~/FindNow.aspx" title="Find Now"  name="10007"/>
  <siteMapNode url="~/TrackNow.aspx" title="Track Now" name="10008" />
</siteMapNode>
<siteMapNode url="" title="Analyse">
  <siteMapNode url="~/Dashboard.aspx" title="Dashboard" name="10009" />
  <siteMapNode url="~/Search.aspx" title="History" name="10010" />
</siteMapNode>
</siteMapNode>
</siteMap>

Following is my code

XElement xelement2 = XElement.Load(Server.MapPath("~/web.sitemap"));
var urlDescList1 = xelement2.Descendants()                                   
    .Where(sel => (string)sel.Attribute("name").Value == "10001")
    .SelectMany(sel => sel.Elements())
    .Select(nd => new
    {
        title = nd.Attribute("title").Value,
        url = nd.Attribute("url").Value
    }).FirstOrDefault();

It gives me null value. I need to read the node that has name attribute value = 10001


Solution

  • I think your query is just slightly off. You need to ensure the element has the name attribute and SelectMany(sel => sel.Elements()) is unnecessary.

    XElement xelement2 = XElement.Load(Server.MapPath("~/web.sitemap"));
    var urlDescList1 =  
        xelement2.Descendants()                                   
            .Where(sel => sel.Attribute("name") != null && sel.Attribute("name").Value == "10001")=
            .Select(nd => new
            {
                title = nd.Attribute("title").Value,
                url = nd.Attribute("url").Value
            })
            .FirstOrDefault();