tags:

views:

241

answers:

1

I need to delete a range of nodes, up to a certain number, in an xml document. What is the most efficient way of doing this? I'm currently iterating over the nodes and deleting them one at time:

int trimFeeds = 20;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MapPath("rss.xml"));

XmlNodeList nodeList = xmlDoc.SelectNodes("rss/channel/item");

if (nodeList.Count > trimFeeds)
{
    int i = 0;
    foreach (XmlNode node in nodeList)
    {
        if (i++ >= trimFeeds)
            node.ParentNode.RemoveChild(node);
    }

    xmlDoc.Save(MapPath("rss.xml"));
}
+1  A: 
int trimFeeds = 20;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MapPath("rss.xml"));

XmlNodeList nodeList = xmlDoc.SelectNodes(string.Format("rss/channel/item[position() > {0}]", trimFeeds));

foreach (XmlNode node in nodeList)
{
    node.ParentNode.RemoveChild(node);
}
xmlDoc .Save(MapPath("rss.xml"));
Lloyd