使用Linq到XML查询google sitemap.xml的问题

问题描述 投票:3回答:1

我有一个Linq-2-XML查询,如果我创建的Google站点地图的urlset元素中填充了属性,则该查询将不起作用,但是如果不存在属性,该查询将可以正常工作。

无法查询:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
  <loc>http://www.foo.com/index.htm</loc>
  <lastmod>2010-05-11</lastmod>
  <changefreq>monthly</changefreq>
  <priority>1.0</priority>
</url>
<url>
  <loc>http://www.foo.com/about.htm</loc>
  <lastmod>2010-05-11</lastmod>
  <changefreq>monthly</changefreq>
  <priority>1.0</priority>
 </url>
</urlset>

可以查询:

<?xml version="1.0" encoding="utf-8"?>
<urlset>
<url>
  <loc>http://www.foo.com/index.htm</loc>
  <lastmod>2010-05-11</lastmod>
  <changefreq>monthly</changefreq>
  <priority>1.0</priority>
</url>
<url>
  <loc>http://www.foo.com/about.htm</loc>
  <lastmod>2010-05-11</lastmod>
  <changefreq>monthly</changefreq>
  <priority>1.0</priority>
 </url>
</urlset>

查询:

XDocument xDoc = XDocument.Load(@"C:\Test\sitemap.xml");
var sitemapUrls = (from l in xDoc.Descendants("url")
                           select l.Element("loc").Value);
foreach (var item in sitemapUrls)   
{       
  Console.WriteLine(item.ToString());
}

这是什么原因?

c# linq-to-xml xml-sitemap
1个回答
7
投票

看到XML中的“ xmlns =”标签吗?您需要指定名称空间。测试您的代码的以下修改:

XDocument xDoc = XDocument.Load(@"C:\Test\sitemap.xml");
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

var sitemapUrls = (from l in xDoc.Descendants(ns + "url")
                    select l.Element(ns + "loc").Value);
foreach (var item in sitemapUrls)
{
    Console.WriteLine(item.ToString());
}
© www.soinside.com 2019 - 2024. All rights reserved.