How to get the content of a tag from a Linq query?

Asked

Viewed 119 times

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 name with the following query 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();
}

Should display as output the name Joao but nothing is displayed in the console and the amount of items returned by the search is 0.

I wonder how I could get the content from the tag name through a LINQ consultation?

  • I have no test, see if changing the place element solves the problem: https://dotnetfiddle.net/eXzoU1

  • In fact I have no way to test here and what exists online, does not have the Assembly necessary. I have seen that I have forgotten the using System.Linq, but this is not the problem.

  • Have you come to any conclusion?

  • I haven’t tested the answer code yet, but I’ve solved the problem, but if you want to answer it would be great :)

  • It’s just that I don’t even know if my solution works. I think the answer given is wrong, but I’m not sure. You can answer too.

1 answer

1

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

The following amendment 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.