gpt4 book ai didi

linq - 使用 Linq to Xml 获取值(value)

转载 作者:行者123 更新时间:2023-12-04 06:06:30 25 4
gpt4 key购买 nike

我有以下 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/ - 最后修改:2011-11-27T08:34:46+00:00
位置: http://www.example.com/123 - 最后修改: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 的新手,请帮忙。

最佳答案

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

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

关于linq - 使用 Linq to Xml 获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8295073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com