Search code examples
c#mvcsitemapproviderxml-sitemap

delete a node from sitemap xml


I have sitemap format as below. I want to delete a complete node that I find loc. For example:

Where a node has <loc>with a value of http://www.my.com/en/flight1. I want to delete the <url> node and his child I want to delete loc than lastmod than priority and than changefreq

<url>
<loc>http://www.my.com/en/flight1
</loc>
<lastmod>2015-03-05</lastmod>
<priority>0.5</priority>
<changefreq>never</changefreq>
</url>


<url>
<loc>
http://www.my.com/en/flight2
</loc>
<lastmod>2015-03-05</lastmod>
<priority>0.5</priority>
<changefreq>never</changefreq>
</url>


<url>
<loc>
http://www.my.com/en/flight3
</loc>
<lastmod>2015-03-05</lastmod>
<priority>0.5</priority>
<changefreq>never</changefreq>
</url>

Solution

  • If you're using C# you should use System.xml.linq (XDocument)

    You can remove a node like so:

    XDocument.Load(/*URI*/);
    
    var elements = document.Root.Elements().Where(e => e.Element("loc") != null && e.Element("loc").Value == "http://www.my.com/en/flight1");
    foreach (var url in elements)
    {
        url.Remove();
    }