AmmaraGafoor
AmmaraGafoor

Reputation: 37

How to Retrieve value of xml node?

I have a xml file like this:

<Contacts>
   <CommandID>
       ShowInstalledProducts
   </CommandID>
</Contacts>

I need to iterate through a list of xml files and retrieve the value of CommandId ( in this case ShowInstalledProducts), for each ...

I am very new to xml. can someone please help me with the same. I am trying to achieve this using Linq. (other solutions are also welcome though)

DirectoryInfo directoryInfo = new DirectoryInfo(@"T:\Commands"); FileInfo[] fileInfo = directoryInfo.GetFiles();

            foreach (FileInfo loop in fileInfo)
            {

                string doc = File.ReadAllText(loop.FullName);
                XmlDocument XMLDoc = new XmlDocument();
                XMLDoc.Load(doc);
                XMLDoc= stripDocumentNamespace(XMLDoc);
                //id = XMLDoc.Descendants("CommandID").First().Value;



            }

This is what i have done till now , im reading the files , and trying to ger the descendants. however there are multiple in each xml file , and i need to retrieve the value of each . stuck here :(

Upvotes: 1

Views: 161

Answers (2)

Sasha
Sasha

Reputation: 8850

fileInfo.SelectMany(fi => XDocument
                           .Load(fi.FullName)
                              .Descendants("CommandID")
                                .Select(e=>e.Value))

This LINQ code should return the list of all CommandId values of all files.

Upvotes: 2

Kjartan
Kjartan

Reputation: 19081

Step 1: Go to linqpad.net and download the Linqpad application. It is a simple editor allowing you to write, run, and play around with Linq expression. Also, it has a lot of built in examples to learn from. (You might have to select Help --> Veiw samples to open this): enter image description here

Step 2: Paste the following code into the editor, and press F5 to run it (make sure C# Statement(s) is selected for "Language" above it though!). Play around and tweak it as you like / need.

var bench = XElement.Parse(@"<Contacts>
                <Node>
                    Something
                </Node>
                <Node>
    Something else
                </Node>
                </Contacts>");

var listOfNodes = bench.Elements(); 
listOfNodes.Dump();

var content = listOfNodes.Select(x => x.Value); 
content.Dump();

This should be enough to get you started. Enjoy! :)

Upvotes: 3

Related Questions