2012-07-31 71 views
3

使用C#搜索XML文件的元素,但越來越以下的XDocument,的XElement:序列中沒有匹配的元素

錯誤:序列中沒有匹配的元素

XNamespace siteNM = "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"; 
      XDocument sitemap = new XDocument 
       (new XDeclaration("1.0", "UTF-8", null), 
        new XElement(siteNM + "siteMap", 
          new XElement(siteNM + "siteMapNode", new XAttribute("title", "Home"), new XAttribute("url", "home.aspx"), new XAttribute("description", "Home")) 
           )); 
    XElement x = sitemap.Root; 

我曾嘗試以下兩種方法搜索元素,但都給我相同的錯誤

1路:

XElement child = x.Descendants("siteMapNode").Where(el => el.Attribute("title") != null && el.Attribute("title").Value == "Home").First(); 

第二路:

XElement child1 = x.Descendants("siteMapNode").First(el => (string)el.Attribute("title") == "Home"); 

請幫助我。 太感謝你了..

回答

5

缺少命名空間

XElement child = x.Descendants(siteNM + "siteMapNode") 
       .First(el => el.Attribute("title") != null && el.Attribute("title").Value == "Home"); 
+0

太感謝你了......你完全對...它幫助我很多......再次感謝你...... – Pritesh 2012-07-31 15:41:43

2

你或許應該在搜索查詢添加namespece還有:

XElement child = x.Descendants(siteNM + "siteMapNode").Where(el => el.Attribute("title") != null && el.Attribute("title").Value == "Home").First();