How to get the contents of a tag through a Linq query?

2

I have XML with the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<pessoas>
    <pessoa>
        <nome>Joao</nome>
        <email>[email protected]</email>
    </pessoa>   
</pessoas>

And I'm trying to get the contents of the tag with the following query of LINQ type:

static void Main(string[] args)
{
    XElement root = XElement.Load("Pessoa.xml");            

    List<string> nomes = root.Elements("pessoas").Elements("pessoa").Select(x => (string)x.Element("nome")).ToList();

    foreach (var n in nomes) Console.WriteLine(n);

    Console.WriteLine(nomes.Count);

    Console.ReadKey();
}

It should display as the output Joao but nothing is displayed on the console and the amount of items returned by the search is 0.

I would like to know how I could get the contents of the tag through a query in LINQ?

    
asked by anonymous 02.07.2016 / 17:27

1 answer

1

The problem is that you are trying to access the Root element again.

The following change already solves your problem:

root.Elements("pessoa").Select(x => (string)x.Element("nome")).ToList();

In your code it looks like this:

static void Main(string[] args)
{
    XElement root = XElement.Load("Pessoa.xml");            

    List<string> nomes = root.Elements("pessoa").Select(x => (string)x.Element("nome")).ToList();

    foreach (var n in nomes) Console.WriteLine(n);

    Console.WriteLine(nomes.Count);

    Console.ReadKey();
}
    
02.07.2016 / 22:24