tags:

views:

36

answers:

3

Hi there,

I currently have to iterate through a larger amount of .xml files and I am bound to Mono (so no brand new .NET LINQ etc.). I use XmlDocument to load each XML file, now my question is, can I use one instance of XmlDocument for all files?

Code Example below:

filePath = "Assets/Units/";
        // Get all files
        string [] files = GetAllFiles(filePath);
        // And iterate through them
        xFile = new XmlDocument(); // create xFile once
        foreach (string file in files)
        {
            xFile = new XmlDocument(); // or create it each time a new file must be opened / parsed?
            // do something
        }
+3  A: 

I think it would be cleaner to create a new instance on each iteration. I'd declare the variable within the loop too. There's no logical association between the documents in each iteration, so why reuse the same object. I suspect it would work, but IMO it's harder to reason about. If you reference to the existing instance "leaks" to elsewhere in your code, the contents will suddenly be changing, probably unexpectedly.

(As an aside, if you're using .NET 3.5 or higher I would strongly consider using LINQ to XML... it's a generally more pleasant API.)

Jon Skeet
Yep, `XDocument` should be available in Mono, too.
0xA3
+2  A: 

In general it should not a problem to create a new XmlDocument instance for every file. I wouldn't do otherwise until you experience any performance/memory problem1. But if you get problems use a profiler first before optimizing, this will show you where the actual problem is.

foreach (string file in GetAllFiles("Assets/Units/"))
{
    XmlDocument xFile = new XmlDocument(); 
    xFile.Load(file);

    // do something
}

1You possibly might see a benefit e.g. when re-using large array structures but I actually doubt you will see a benefit with XmlDocument as loading a new document will allocate new memory anyway.

0xA3
+2  A: 

If you are concerned about performance, and are not updating the XML files it would be worthwhile to consider using XPathDocument instead of XmlDocument.

Nick Jones