C# 使用LINQ到XML查询站点地图

C# 使用LINQ到XML查询站点地图,c#,xml,linq-to-xml,sitemap,C#,Xml,Linq To Xml,Sitemap,我有一个ASP.NETMVC网站。此网站的网站地图如下所示: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.mysite.com/contact</loc> <lastmod>2013-06-04</lastmod> <changefreq>never</cha

我有一个ASP.NETMVC网站。此网站的网站地图如下所示:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.mysite.com/contact</loc>
    <lastmod>2013-06-04</lastmod>
    <changefreq>never</changefreq>
  </url>
  <url>
    <loc>http://www.mysite.com/contact-us</loc>
    <lastmod>2013-06-04</lastmod>
    <changefreq>never</changefreq>
  </url>
  <url>
    <loc>http://www.mysite.com/about/books</loc>
    <lastmod>2013-06-18</lastmod>
    <changefreq>monthly</changefreq>
  </url>
  <url>
    <loc>http://www.mysite.com/about/blog</loc>
    <lastmod>2012-05-02</lastmod>
    <changefreq>never</changefreq>
  </url>
  <url>
    <loc>http://www.mysite.com/about/blog/post-1</loc>
    <lastmod>2012-05-02</lastmod>
    <changefreq>never</changefreq>
  </url>
  <url>
    <loc>http://www.mysite.com/about/blog/post-2</loc>
    <lastmod>2012-02-15</lastmod>
    <changefreq>never</changefreq>
  </url>
</urlset>
我试图弄清楚如何用C语言中的LINQtoXML查询这个站点地图。我试图编写一个只返回博客文章条目的查询。博客文章条目的loc属性值以开头。目前,我正在成功加载和查询站点地图。然而,我不知道如何只过滤博客文章,然后按lastmod值排序。这就是我到目前为止所做的:

XDocument sitemap = XDocument.Load(Server.MapPath("/resources/sitemap.xml"));
IEnumerable<XElement> blogs = from post in sitemap.Descendants("url")
                              select post;

我如何过滤到我的博客帖子?我对URL的查询似乎不起作用。

您的XML文档使用默认名称空间,因此您也必须在查询中使用它:

var ns = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9");

IEnumerable<XElement> blogs = from post in sitemap.Root.Elements(ns + "url")
                              where ((string)post.Element(ns + "loc") ?? string.Empty).StartsWith("http://www.mysite.com/about/blog/")
                              select post;
我用了stringpost.Elements+loc??为空,以确保在元素不存在时不会引发异常,但如果您确定每个元素中都有,则可以将其替换为stringpost.Elementns+loc