【问题标题】:Getting Value using Linq to Xml使用 Linq to Xml 获取价值
【发布时间】:2011-11-28 11:22:00
【问题描述】:

我有以下 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>

我想获取链接及其修改日期。例如结果应如下所示:

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

我使用了以下代码,但似乎没有任何效果:

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);
}

即使这个查询也不返回任何内容:

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

我是 Linq to Xml 的新手,请帮忙。

【问题讨论】:

  • root.Elements().Where(element =&gt; element.Name.LocalName == "sitemap") 可能也可以,但不建议这样做。

标签: linq linq-to-xml


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2013-01-10
    相关资源
    最近更新 更多