2017-09-11 48 views
0

我想將XML頁面加載到DataGridView。在頁面上嵌套節點「立方體」。我有LINQ表達式的問題,因爲它始終是null從XML加載數據後DataGridView爲空

XElement xml = XElement.Load("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); 
var xmlData = from item in xml.Descendants("Cube") 
       select new { 
       Currency = item.Attribute("currency").Value, 
       Rate = item.Attribute("rate").Value      
       }; 
dataGridView1.DataSource = xmlData.ToList(); 

更新

我使用XmlNodeList和我對象doc標籤 「魔方」 通過。目前在循環中,我有33個節點多維數據集,我想顯示子元素貨幣和利率。但是我有一個錯誤「System.NullReferenceException:'對象引用未設置爲對象實例。'

private void LoadCurrency() 
    { 
     XmlDocument doc = new XmlDocument(); 
     XmlNodeList nodeList; 
     doc.Load("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); 
     nodeList = doc.GetElementsByTagName("Cube"); 
     for(int i=0;i<nodeList.Count;i++) 
     { 
      string str = String.Format("Currency={0} Rate={1}",nodeList[i].ChildNodes.Item(1).InnerText, nodeList[i].ChildNodes.Item(2).InnerText); 
      listBox1.Items.Add(str.ToString()); 
     } 
    } 

任何幫助或建議,歡迎

+0

'Cube'不加載文件的根元素的根元素是'GESMES :Envelope' so'xml.Descendants(「Cube」)'返回空/空,這是正確的。 – zx485

+0

這是一個糟糕的API,它在3層嵌套中命名元素完全相同。 – Crowcoder

回答

0

設置ItemsSource來代替:。

dataGridView1.ItemsSource = xmlData.ToList();