Roel
Roel

Reputation: 764

XML records to an array in C#

I have been trying all morning and I can't seem to get this working. I have an XML file as follows:

<?xml version="1.0" encoding="utf-8" ?>
<Details>
  <cityItems>
    <city>Amsterdam</city>
    <city>New York</city>
  </cityItems>
  <streetItems>
    <street>Mainstreet</street>
    <street>Secondstreet</street>
  </streetItems>
</Details>

I am trying to get the output a bit like this;

string[] cities = { "Amsterdam", "New York" };
string[] streets = { "Mainstreet", "Secondstreet" };

Streets and cities are not linked to each other or anything. I can't seem to find the right examples on the internet to get this working.

Could you please help me or point me in the right direction? Thanks.

Upvotes: 0

Views: 91

Answers (2)

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

I've changed you xml so that it has correct closing node </cityItems>

var xml = XDocument.Parse(str);

Func<string, string[]> readAllCities = 
                            nodeName => 
                                     xml.Descendants(nodeName)
                                        .SelectMany(node => node.Elements("city")
                                                                .Select(v => v.Value))
                                        .ToArray();


string[] streets  = readAllCities("streetItems");
string[] cities  = readAllCities("cityItems");

I will left old version with a code duplicate, so that you can chose what is better and integrate it more comfortable into your solution

string[] cities = xml.Descendants("cityItems")
                     .SelectMany(node => node.Elements("city")
                                             .Select(v => v.Value))
                     .ToArray();


string[] strets = xml.Descendants("streetItems")
                     .SelectMany(node => node.Elements("city")
                                             .Select(v => v.Value))
                     .ToArray();

Upvotes: 2

Jibran Khan
Jibran Khan

Reputation: 3256

You need to use LINQ to XML i guess and loop the result to the array. Here is something can point you the right direction

    XDocument xdoc = XDocument.Load("data.xml");

   //Run query
    var lv1s = from lv1 in xdoc.Descendants("level1")
       select new { 
           Header = lv1.Attribute("name").Value,
           Children = lv1.Descendants("level2")
       };

Upvotes: 0

Related Questions