gpt4 book ai didi

.net - Linq2XML,为什么 Element()、Elements() 不工作?

转载 作者:数据小太阳 更新时间:2023-10-29 02:09:47 26 4
gpt4 key购买 nike

我正在尝试遍历一个简单的站点地图(即时添加和删除元素。)这是示例布局

<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
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">
<url>
<loc>http://mysite.com/</loc>
<priority>1.00</priority>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://mysite.com/Default.aspx</loc>
<priority>0.80</priority>
<changefreq>daily</changefreq>
</url>
</urlset>

奇怪的是,当我在加载文档后尝试使用 Element() 方法访问子元素时,它为空,Elements() 也为空,所以我无法遍历它们。 Nodes() 方法具有元素。

这是我写的代码

XElement siteMap = XElement.Load(Server.MapPath("~/sitemap.xml"));

//First remove all article nodes
foreach (XElement elem in siteMap.Elements())
{
XElement loc = elem.Element("loc");
if (loc.Value.Contains("http://mysite.com/articles/"))
elem.Remove();
}

无论我做什么来尝试检索 elem (Element, Elements) 的元素,我都会得到一个 null。

有什么问题吗?这段代码应该运行。不是吗?

最佳答案

var doc = XDocument.Load(Server.MapPath("~/sitemap.xml"));
foreach (XElement elem in doc.Root.Elements()) {
var loc = elem.Element(XName.Get("loc","http://www.sitemaps.org/schemas/sitemap/0.9") );
if (loc.Value.Contains("http://astrobix.com/articles/"))
elem.Remove();
}

您也可以改为执行以下操作:

doc.Root.Elements()
.Where(x => x.Element(XName.Get("loc", "http://www.sitemaps.org/schemas/sitemap/0.9"))
.Value.Contains("http://astrobix.com/articles/"))
.Remove();

关于.net - Linq2XML,为什么 Element()、Elements() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569208/

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