jack
jack

Reputation:

LINQ-to-XML: Selecting specific node value

<PKT>
   <Result Name="GetBalance" Success="1">
      <Returnset>
         <Balance Type="int" Value="0" />
      </Returnset>
   </Result>
</PKT>

Best way to get the value of Balance with LINQ-to-XML?

Upvotes: 1

Views: 3670

Answers (3)

ocodo
ocodo

Reputation: 30248

If you wanted to only get the value from the first occurrence of Balance, you could do.

var balance = (from n in XDocument.Load("MyFile.xml").Descendents("Balance")
               select n.Attributes("Value").Value).ToList().First();

Upvotes: 0

Yannick Motton
Yannick Motton

Reputation: 35971

var values = from e in XDocument.Load("MyFile.xml").Descendants("Balance")
             select e.Attribute("Value").Value;

foreach (var e in values)
{
    Console.WriteLine(e);
}

Upvotes: 3

Dante
Dante

Reputation: 3891

XDocument doc = XDocument.Load("MyFile.xml");
IEnumerable<XElement> elements = doc.Descendants("Balance");

foreach (XElement e in elements)
{
    Console.Write(e.Attribute("Value").Value);
}

You can do it this way. I typed the code directly here, you may want to confirm any typos.

Upvotes: 2

Related Questions