从XML

时间:2017-09-11 10:59:37

标签: c# xml datagridview

我想将XML页面加载到DataGridView。页面上是嵌套节点" Cube"。我对LINQ表达式有问题,因为它始终是null

 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标记" Cube"。目前在循环中我有33个节点Cube,我想显示子元素货币和汇率。但是我有一个错误" 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());
        }
    }

欢迎任何帮助或建议。

1 个答案:

答案 0 :(得分:0)

设置ItemsSource代替:

dataGridView1.ItemsSource = xmlData.ToList();