简体   繁体   中英

XDocument, XElement : Sequence contains no matching element

Searching element of xml file using C# but getting following

Error: Sequence contains no matching element

    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;

I have tried following two methods for searching element but both give me same error .

1st way:

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

2nd Way:

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

please help me. Thank you so much..

missing namespace

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

你可能也应该在搜索查询中添加namespece:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM