views:

164

answers:

2

Hi all,

How do I use Linq to extract a single XML attribute form each XML file in a directory and put that element in a C# list. Do I have to loop thru each file one-by-one? The XML files are quite large so I'd like to do this without loading the entire file into memory.

Thanks, j

+1  A: 

You do have to go through every file, and this will mean at least parsing enough of the XML content of each file to get to the required attribute.

XDocument (i.e. LINQ to SQL) will parse and load the complete document in each case, so you might be better using an XmlReader instance directly. This will require more work: you will have to read the XML nodes until you get to the right one, keeping track of where you are.

Richard
Oh man, using `XmlReader` directly is unbelievable tedious.
ChaosPandion
+2  A: 

Unless the files are massive (100 MB+) I would be unable to turn down the elegance of this code:

var result = Directory.GetFiles(filePath)
    .Select(path => XDocument.Load(path))
    .Select(doc => doc.Root.Element("A").Attribute("B").Value)
    .ToList();

I really hope your XML files are not that big though...

ChaosPandion
@ChaosPandion, super elegant
msarchet