2009-02-20 25 views
4

我想遍历一个简单的网站地图(添加和删除在飞行中的元素。)这是样板布局Linq2XML,为什么Element(),Elements()不工作?

<?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> 

古怪,当我尝试使用元素()方法加载后访问的子元素该文档是空的,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的(元素,元素)的元素的代码,我得到一个空。

什么可能是错的?这段代码应该运行。不是吗?

回答

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

对不起迈赫达德,没有工作。我得到一个NullReferenceException在foreach行(siteMap.Element(“urlset”)。元素(“url”)) 这正是我所面临的问题......这是否与你所说的XML数据一起工作? – 2009-02-20 11:37:14