2013-09-29 43 views
0
<response> 
    <payment loanType="thirtyYearFixed"> 
    <rate>4.09</rate> 
    <monthlyPrincipalAndInterest>410</monthlyPrincipalAndInterest> 
    <monthlyMortgageInsurance>54</monthlyMortgageInsurance> 
    </payment> 
</response> 

我的問題是我如何從費率,monthlyPrincipalAndInterest和MonthlyMortgageInsurance獲取信息?我想盡不同的方式和之前發佈這個使用下面的代碼作爲我的最後的手段使用的XDocument都已​​停止如何使用C#中的XmlDocument在屬性元素中的子元素中獲取XML信息?

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

這僅僅是速度子元素的代碼。我已經在我解析的XML文件中的這個部分之前獲得了所有信息,但是我用這個命令打了一堵磚牆,似乎無法弄清楚。我甚至使用XMLNodeList和base // // response/payment [@ loanType ='thirtyYearFixed']作爲變量,然後是nodeVar [「rate」]。InnerText仍然有空引用錯誤。

我有一種感覺,這將是我看過的一些小片,但我不僅用完了時間不足的選項。

回答

1

也許嘗試這樣的事:

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

這將執行的很好!如果只有我沒有犯XDocument而不是XmlDocument的巨大錯誤......回到我的繪圖板。 –

+0

如果我用我的HTTP響應使用這個方法,它會出現空,如果我只使用生成的文件的URL,那麼它出於某種原因顯示0。 –

+0

問題已解決。顯然,我的解析中沒有錯誤,但是在我的HTTP請求中出現錯誤。謝謝您的幫助!上面的代碼完全可以用於獲取所需的信息。 –

相關問題