簡體   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>

我的問題是如何從費率,monthlyPrincipalAndInterest和monthlyMortgageInsurance中獲取信息? 在發布此代碼之前,我嘗試了各種方法,並使用以下代碼停止了XDocument的使用:

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

這只是rate子元素的代碼。 在解析的XML文件中,我已經獲得了這部分之前的所有信息,但是我為此碰到了牆,似乎無法弄清楚。 我什至使用XMLNodeList和// response / payment [@ loanType ='thirtyYearFixed']作為變量,然后使用nodeVar [“ rate”]。InnerText作為變量,仍然出現空引用錯誤。

我覺得這只是我看過的一小部分,但我不僅會用光我的時間。

也許嘗試這樣的事情:

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