4

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

<?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() 方法访问子元素时,它为 null,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) 的元素,我都会得到一个空值。

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

4

1 回答 1

3
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();
于 2009-02-20T11:32:00.050 回答