1
<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?

3 Answers 3

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

foreach (var e in values)
{
    Console.WriteLine(e);
}
Sign up to request clarification or add additional context in comments.

Comments

2
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.

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.