Ali
Ali

Reputation: 1678

Getting Value using Linq to Xml

I have the following Xml structure:

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <sitemap>
  <loc>http://www.example.com/</loc>
  <lastmod>2011-11-27T08:34:46+00:00</lastmod>
 </sitemap>
 <sitemap>
  <loc>http://www.example.com/123</loc>
  <lastmod>2011-11-27T08:34:46+00:00</lastmod>
 </sitemap>
</sitemapindex>

I want to get the links along with their modification date. e.g. the result should look like:

loc: http://www.example.com/ - lastmod: 2011-11-27T08:34:46+00:00
loc: http://www.example.com/123 - lastmod: 011-11-27T08:34:46+00:00

I've used the following code but nothing seems to work:

XElement root = XElement.Load("data.xml");

var results = from el in root.Elements("sitemap")
              select new
              {
                  loc = (string) el.Element("loc"),
                  lastmod = (string) el.Element("lastmod")
              };


foreach (var result in results)
{
    Console.WriteLine("loc:" + result.loc + " - lastmod:" + result.lastmod);
}

even this query doesn't return anything:

var results = from el in root.Elements("sitemap")
              select el;

I am new to Linq to Xml, Please help.

Upvotes: 2

Views: 90

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504122

The problem is you're trying to select elements without namespaces. Try this instead:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
var results = from el in root.Elements(ns + "sitemap")
              select new
              {
                  loc = (string) el.Element(ns + "loc"),
                  lastmod = (string) el.Element(ns + "lastmod")
              };

Upvotes: 3

Related Questions