2015-02-23 98 views
1

我一直在嘗試使用LINQ讀取web.sitemap,但無法完成。以下是我的web.sitemap無法讀取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> 

以下是我的代碼

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(); 

它給了我null值。我需要讀取具有名稱屬性值的節點值= 10001

+0

xml包含一個名稱空間。你在查詢中不尊重這一點。 – 2015-02-23 12:22:09

+0

@ J.Steen您能否爲我發佈查詢.. – 2015-02-23 12:27:04

+0

http://stackoverflow.com/questions/2340411/use-linq-to-xml-with-xml-namespaces – 2015-02-23 12:27:41

回答

2

我認爲您的查詢稍微偏離了。您需要確保元素具有name屬性,並且不需要SelectMany(sel => sel.Elements())

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();