AKD
AKD

Reputation: 3966

Reading data from XML into an array

I've an XML file, in which I'm saving temporary data(index & name of columns) as given below:

-<NewDataSet> 
    -<USERROWCOL> 
          <COL>2</COL> 
          <Name>Name</Name> 
     </USERROWCOL> 
    -<USERROWCOL> 
          <COL>8</COL> 
          <Name>PDC</Name> 
     </USERROWCOL>
 <NewDataSet>

I want to read all COLs in an array using C# like it will be an array( {2, 8} ). Can anyone help me about this?

Upvotes: 7

Views: 20687

Answers (2)

Vishal Suthar
Vishal Suthar

Reputation: 17194

Here is a LINQ to XML Version:

string[] arr = XDocument.Load(@"C:\xxx.xml").Descendants("Name")
                        .Select(element => element.Value).ToArray();

This will give all the Name element from the document.

Upvotes: 11

Jon Skeet
Jon Skeet

Reputation: 1500515

LINQ to XML makes this very easy:

var document = XDocument.Load("file.xml");
var array = document.Descendants("COL").Select(x => (int) x).ToArray();

That's assuming you just want every COL element in the document, and every element's value will be an integer.

Upvotes: 8

Related Questions