Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from XML into an array

Tags:

arrays

c#

xml

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?

like image 419
Ashok Damani Avatar asked Jan 16 '13 08:01

Ashok Damani


2 Answers

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.

like image 178
Vishal Suthar Avatar answered Oct 12 '22 09:10

Vishal Suthar


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.

like image 24
Jon Skeet Avatar answered Oct 12 '22 08:10

Jon Skeet