2013-12-10 56 views
1

查询一个网站地图,比如这个:如何利用给定一个网站地图一个XDocument LINQ查询

<?xml version=\"1.0\" encoding=\"UTF-8\" ?> 
<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:mobile=\"http://www.google.com/schemas/sitemap-mobile/1.0\"> 
<sitemap><loc>http://www.whyisxdocumentsuchapain.com/sitemap.kill.xml</loc><lastmod>2013-12-10T18:34:09Z</lastmod></sitemap> 
<sitemap><loc>http://www.whyisxdocumentsuchapain.com/sitemap.destroy.xml</loc><lastmod>2013-12-10T18:34:09Z</lastmod></sitemap> 
<sitemap><loc>http://www.whyisxdocumentsuchapain.com/sitemap.pillage.xml</loc><lastmod>2013-12-10T18:34:09Z</lastmod></sitemap> 
<sitemap><loc>http://www.whyisxdocumentsuchapain.com/sitemap.etc.xml</loc><lastmod>2013-12-10T18:34:09Z</lastmod></sitemap> 
</sitemapindex> 

我怎么会用一个XDocument LINQ查询来获取loc节点内的四个网址吗?

它似乎完全击败了我。

回答

5
var ns = xdoc.Root.GetDefaultNamespace(); 
var urls = xdoc.Root.Elements().Elements(ns + "loc").Select(l => (string)l); 

结果:

"http://www.whyisxdocumentsuchapain.com/sitemap.kill.xml", 
"http://www.whyisxdocumentsuchapain.com/sitemap.destroy.xml" 
"http://www.whyisxdocumentsuchapain.com/sitemap.pillage.xml" 
"http://www.whyisxdocumentsuchapain.com/sitemap.etc.xml" 
+1

好极了,谢谢你。 – David