2011-11-28 59 views
2

我有以下XML结构:使用LINQ获得价值为XML

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

我想要得到的链接与他们的修改日期。例如结果应该是这样的:

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

我用下面的代码,但似乎没有任何工作:

的XElement根= 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); 
} 

即使该查询不返回任何内容:

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

我是新来的LINQ to XML,请帮助。

+0

'root.Elements()。其中​​(element => element.Name.LocalName ==“sitemap”)'可能会起作用,尽管它不被推荐。 –

回答

3

问题是你试图选择没有命名空间的元素。试试这个:

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") 
       }; 
+0

非常感谢Jon的完美工作。 :) – Ali