Reading data from XML to array

I have an XML file in which I save temporary data (index and column name) as follows:

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

I want to read all the COL in an array using C #, as if it would be an array ( {2, 8} ). Can someone help me with this?

+7
source share
2 answers

Here is the LINQ to XML version:

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

This will give the entire Name element of the document.

+9
source

LINQ to XML makes this very simple:

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

Assuming you just need every COL element in the document, and each element value will be an integer.

+8
source

All Articles