tags:

views:

67

answers:

3

Hi I am working on a project, in which I need to write xml to a file, this happens in a for loop,

that is

for(int i = 0; i < screens.length; screens++)
{
    XMLDocument allScreens = new XMLDocument();
    allScreens.Load(allScreeensPath);
    XMLNode node = allScreens.Select("//Screen[@name='" + screens[i].name + "']");
    allScreens.Remove(node);
    allScreens.Add(nweNode);
    allScreens.Save(allScreeensPath);
}

basicalyy the xml document is accessed, modified and saved in a for loop, this work some times. and some thimes I get the following error ,

I tries using text readers, text writers to do file operations( so that I can close, dispose the writers) but the error persists, Can anyone suggest as to how I can get through this ??

Thanks in Advance.

+4  A: 

The simplest approach would be to load it once, do all the processing you need to and then save it once.

I don't know why it's not working at the moment, admittedly - but I don't see any need to keep loading and saving. For example, here's an alternative version of your code:

XMLDocument allScreens = new XMLDocument();
allScreens.Load(allScreeensPath);
foreach (Screen screen in screens)
{
    XMLNode node = allScreens.Select("//Screen[@name='" + screen.Name + "']");
    allScreens.Remove(node);
    allScreens.Add(newNode);
}
allScreens.Save(allScreeensPath);
Jon Skeet
+5  A: 

This might be (not sure though) because you re-open the XML file for each iteration of your loop, which seems unnnecessary. Instead open the document before the loop, perform the loop, and then save it.

XMLDocument allScreens = new XMLDocument();
allScreens.Load(allScreeensPath);

for(int i = 0; i < screens.length; screens++)
{
    XMLNode node = allScreens.Select("//Screen[@name='" + screens[i].name + "']");
    allScreens.Remove(node);
    allScreens.Add(nweNode);
}
allScreens.Save(allScreeensPath);

(I am not sure where nweNode comes into the picture in the code sample, but I leave it in since I only reworked the original code sample)

Fredrik Mörk
A: 

It looks like you are updating the same file multiple times?

You should perform all the updates to your in-memory XMLDocument, and after the for loop, save to the file.

MattH