Question

Given a sitemap such as this:

<?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>

How would I use an XDocument linq query to get the four URLs inside the loc nodes?

It appears to completely defeat me.

Was it helpful?

Solution

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

Result:

"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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top