Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read XML file in c#?

I have following XML file, i want to know best way to read this XML file

<MyFile> 
  <Companies> 
    <Company>123</Company> 
    <Company>456</Company>
    <Company>789</Company> 
  </Companies> 
</MyFile>

As an output i need collection of values like "123,456,789" or it could be array of string[]

Can we use Linq to xml? How?

like image 616
Hemant Kothiyal Avatar asked Jun 27 '12 11:06

Hemant Kothiyal


2 Answers

var xdoc = XDocument.Load(PATH_TO_FILE);
var companies = xdoc.Descendants("Company").Select(c => (string)c).ToArray();

This will give you a string[].

like image 124
Daren Thomas Avatar answered Sep 30 '22 19:09

Daren Thomas


Use LINQ to XML, Include using System.Xml.Linq;

   XDocument xmlDoc = XDocument.Load("yourfile.xml");
   var test = xmlDoc.Descendants("Companies").Elements("Company").Select(r => r.Value).ToArray();
   string result = string.Join(",", test);

Output would be:

123,456,789

like image 41
Habib Avatar answered Sep 30 '22 17:09

Habib