代码之家  ›  专栏  ›  技术社区  ›  Cyril Gupta

linq2xml,为什么element(),elements()不起作用?

  •  4
  • Cyril Gupta  · 技术社区  · 16 年前

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

    <?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()方法访问子元素时,它是空的,element s()也是空的,所以我不能遍历它们。但是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的元素(元素、元素),我都会得到一个空值。

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

    1 回复  |  直到 16 年前
        1
  •  3
  •   Mehrdad Afshari    16 年前
    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();