Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net Linq2XML,为什么不是&x27;t Element(),Elements()工作吗?_.net_Xml_Linq_Linq To Xml - Fatal编程技术网

.net Linq2XML,为什么不是&x27;t Element(),Elements()工作吗?

.net Linq2XML,为什么不是&x27;t Element(),Elements()工作吗?,.net,xml,linq,linq-to-xml,.net,Xml,Linq,Linq To Xml,我正在尝试遍历一个简单的站点地图(动态添加和删除元素)。这是示例布局 <?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.site

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

<?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>
无论我如何尝试检索elem的元素(Element,elements),我都会得到一个空值

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

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();

对不起,迈尔达,那没用。我在foreach行(siteMap.Element(“urlset”).Element(“url”))中得到一个NullReferenceException,这正是我面临的问题。。。这对您这边的XML数据有效吗?这个新的有效。该问题是由命名空间中定义的元素名引起的。如果显式指定名称空间,它将正常工作。
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();