2015-02-23 134 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();