简体   繁体   English

如何在C#中使用XmlDocument从具有属性的Element的子元素中获取XML信息?

[英]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? 我的问题是如何从费率,monthlyPrincipalAndInterest和monthlyMortgageInsurance中获取信息? I have tried every different way and have stopped with XDocument using the following code as my last resort prior to posting this: 在发布此代码之前,我尝试了各种方法,并使用以下代码停止了XDocument的使用:

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

This is just the code for the rate child element. 这只是rate子元素的代码。 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. 在解析的XML文件中,我已经获得了这部分之前的所有信息,但是我为此碰到了墙,似乎无法弄清楚。 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. 我什至使用XMLNodeList和// response / payment [@ loanType ='thirtyYearFixed']作为变量,然后使用nodeVar [“ rate”]。InnerText作为变量,仍然出现空引用错误。

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. 我觉得这只是我看过的一小部分,但我不仅会用光我的时间。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM