gpt4 book ai didi

c# - 使用 Linq to XML 查询 google sitemap.xml 的问题

转载 作者:行者123 更新时间:2023-11-30 14:19:23 25 4
gpt4 key购买 nike

我有一个 Linq-2-XML 查询,如果我创建的 google 站点地图的 urlset 元素填充了属性,该查询将无法工作,但如果不存在任何属性,该查询将正常工作。

无法查询:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.foo.com/index.htm</loc>
<lastmod>2010-05-11</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://www.foo.com/about.htm</loc>
<lastmod>2010-05-11</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
</urlset>

可以查询:

<?xml version="1.0" encoding="utf-8"?>
<urlset>
<url>
<loc>http://www.foo.com/index.htm</loc>
<lastmod>2010-05-11</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://www.foo.com/about.htm</loc>
<lastmod>2010-05-11</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
</urlset>

查询:

XDocument xDoc = XDocument.Load(@"C:\Test\sitemap.xml");
var sitemapUrls = (from l in xDoc.Descendants("url")
select l.Element("loc").Value);
foreach (var item in sitemapUrls)
{
Console.WriteLine(item.ToString());
}

这是什么原因?

最佳答案

看到 XML 中的“xmlns=”标签了吗?您需要指定命名空间。测试代码的以下修改:

XDocument xDoc = XDocument.Load(@"C:\Test\sitemap.xml");
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

var sitemapUrls = (from l in xDoc.Descendants(ns + "url")
select l.Element(ns + "loc").Value);
foreach (var item in sitemapUrls)
{
Console.WriteLine(item.ToString());
}

关于c# - 使用 Linq to XML 查询 google sitemap.xml 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2811768/

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