Joe Kasavage
Joe Kasavage

Reputation: 522

How to get XML information from a child in an Element with a attribute using XmlDocument in C#?

<response>
  <payment loanType="thirtyYearFixed">
    <rate>4.09</rate>
    <monthlyPrincipalAndInterest>410</monthlyPrincipalAndInterest>
    <monthlyMortgageInsurance>54</monthlyMortgageInsurance>
  </payment>
</response>

My question is how do I get the information from rate, monthlyPrincipalAndInterest, and monthlyMortgageInsurance? I have tried every different way and have stopped with XDocument using the following code as my last resort prior to posting this:

Rate = root.SelectSingleNode("//response/payment[@loanType='thirtyYearFixed']/rate").InnerText;

This is just the code for the rate child element. I have get all information prior to this portion in the XML file I am parsing but I hit a brick wall with this and can't seem to figure it out. I've even used XMLNodeList with the base //response/payment[@loanType='thirtyYearFixed'] as the variable then nodeVar["rate"].InnerText and still got a null reference error.

I have a feeling this is going to be some small piece I over looked but I'm not only running out of options I'm running out of time.

Upvotes: 0

Views: 115

Answers (1)

Dylan
Dylan

Reputation: 165

Maybe try something like this:

var xdoc = XDocument.Load(@"C:\Temp\doc.xml");
var node = xdoc.XPathSelectElements("./response/payment[@loanType='thirtyYearFixed']");
var query = from payment in  node             
            select new
            {
                rate                        = payment.XPathSelectElement("rate"),
                monthlyPrincipalAndInterest = payment.XPathSelectElement("monthlyPrincipalAndInterest"),
                monthlyMortgageInsurance    = payment.XPathSelectElement("monthlyMortgageInsurance")

            };

    foreach (var v in query)
    {
        Console.WriteLine(v.rate.Value);
        Console.WriteLine(v.monthlyPrincipalAndInterest.Value);
        Console.WriteLine(v.monthlyMortgageInsurance.Value);
    }

Upvotes: 1

Related Questions