Click here to Skip to main content
15,299,443 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function in which it modifies an XML file by removing all the node other than the node with specified id. My code is:

C#
public static void myTry()
       {
           string pathname = @"c:\Run\itemsnew.xml";
           var xdoc = XDocument.Load(pathname);
           foreach (var item in xdoc.XPathSelectElements("/items/superitem/item[@id!='2']"))
           {
               item.Remove();
               xdoc.Save(pathname);
               //myTry();
           }

           //xdoc.Save(@"d:\itemsnew.xml");

           Console.ReadLine();
       }



What my problem is this loop is only getting executed once. That is, if i have 4 nodes with id's 1,2,3 and 4, the XML which i get after the program execution is an XML with 3 nodes having Id's 2,3 and 4 but I need the XML with a single node, ie, the node with id=2. If i call my function inside itself (like i have commented here in line 10) i get the desired result. But how else can i achieve the same? How should i code the loop so that the function removes all the nodes with id!=2 in a single call?
Posted
Comments
Joezer BH 15-Sep-13 3:04am
   
Out or curiosity: Why would you want to save on each iteration (instead of at the end)?

1 solution

As Canny said, you should not save each time through your loop--you're doing too much work that way. But what's causing your problem is the Remove inside the loop--see http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.remove.aspx[^]

If removing is all you're doing, you don't need to loop, just remove:
C#
string pathname = @"d:\itemsnew.xml";
var xdoc = XDocument.Load(pathname);
xdoc.XPathSelectElements("/items/superitem/item[@id!='2']").Remove();
xdoc.Save(pathname);


If you are doing more inside the loop, then convert your element enumeration to a list using ToList, as the MS link describes.
   
Comments
djay99 17-Sep-13 6:57am
   
Thank you sir..That did the work.. I'll try avoiding these silly mistakes next time.. :):)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900