XML query does not return values

Asked

Viewed 128 times

1

The goal was to return the xml values but it is not returning anything:

using System;
using System.Xml.Linq;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Threading;


namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {

                StreamReader strm = new StreamReader("C:\\Users\\Visita\\Desktop\\test.xml");
                XDocument xd = XDocument.Load(strm);

                var consulta = from p in xd.Descendants("tb")
                               where p.Element("simbolo").Value == "H"
                               select new
                               {
                                   sa = Convert.ToString(p.Element("simbolo")),
                                   nm = Convert.ToString(p.Element("nAtomic"))
                               };

                foreach (var rs in consulta.ToArray())
                {
                    Console.WriteLine(Convert.ToString(rs.nm));
                } 
                  Console.Read();
        }
    }
}

XML:

<?xml version="1.0" encoding="utf-8" ?>
<Itens>
  <tb>
    <simbolo>G</simbolo>
    <nAtomic>56</nAtomic>
    <valencia>5</valencia>
  </tb>
  <tb>
    <simbolo>Ga</simbolo>
    <nAtomic>565</nAtomic>
    <valencia>55</valencia>
  </tb>

</Itens>

Not returning any value, which error?

1 answer

4


Remove the Where, because with the Where it will filter only the <simbolo>H</simbolo>, and there’s no record of that tag.

where p.Element("simbolo").Value == "H"             

Thus remaining:

StreamReader strm = new StreamReader("C:\\Users\\Visita\\Desktop\\test.xml");
XDocument xd = XDocument.Load(strm);

var consulta = from p in xd.Descendants("tb")
    select new
    {
        sa = Convert.ToString(p.Element("simbolo")),
        nm = Convert.ToString(p.Element("nAtomic"))
    };

    foreach (var rs in consulta.ToArray())
    {
        Console.WriteLine(Convert.ToString(rs.nm));
    } 
Console.Read();
  • The problem is that this way I’m getting all the values and not just the H (in case I would put a variable to choose which value would be) Edit: Ahh n had H in xml ops hehe OBG, got kk

  • @Lucas, if the answer is right, please put as the correct answer. Thank you

Browser other questions tagged

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