Błąd przy odczytywaniu wartości atrybutów węzłów w XML

0

Witam wszystkich. Chciałbym wczytać ze strony internetowej nazwy walut i ich wartości. Wykorzystałem w tym celu XmlNodeList i przekazałem w tagu "Cube". Obecnie w pętli mam 33 węzły "Cube" i chciałbym wyświetlić wartość atrybutów currency i rate . Ale mam błąd "System.NullReferenceException:" Odwołanie do obiektu nie zostało ustawione na instancję obiektu ".

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

Wszelka pomoc lub sugestia są mile widziane.

0

NodeList otrzymasz przez doc.DocumentElement i wtedy ChildNodes albo jakieś tam wyszukiwanie. Brakuje Ci tego DocumentElement.

1

Zła kolejność. Zauważ, że tam masz rekursywnie sekcje Cube. Waluty zaczynają się do drugiej iteracji:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace NullTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = new XmlDocument();
            doc.Load("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

            var nodes = doc.GetElementsByTagName("Cube");
            var dateNodePos = 1;
            var currencyNodesPos = 2;

            Console.WriteLine($"Date: {nodes[dateNodePos].Attributes["time"].Value}");
            for (int i = currencyNodesPos; i < nodes.Count; i++)
            {
                Console.WriteLine($"Currency: {nodes[i].Attributes["currency"].Value}, Rate: {nodes[i].Attributes["rate"].Value} ");

            }
        }
    }
}
0

Mam jeszcze jeden problem z wyświetleniem wierszy w 'dataGridView'. Stworzyłem kolumny 'Currency' i 'Rate'. A następnie chciałem przekazać do kolumn odpowiednie wiersze z danymi. Po odpaleniu programu w wierszu Currency i Rate mam ostatnią nazwę waluty i ostatnią wartość. Ktoś może wie jak zrobić aby pokazało wszystkie wiersze z odpowiednimi wartościami?

 for (int i =2; i < nodeList.Count; i++)
            {
              
                    string str = String.Format("Currency= {0}  Rate= {1}", nodeList[i].Attributes["currency"].InnerText, nodeList[i].Attributes["rate"].InnerText);
                    listBox1.Items.Add(str.ToString());


                DataTable table = new DataTable();
                table.Columns.Add("Currency",typeof(string));
                table.Columns.Add("Rate", typeof(string));
                DataRow row = table.NewRow();
                row[0] = nodeList[i].Attributes["currency"].InnerText;
                row[1] = nodeList[i].Attributes["rate"].InnerText;
                

                table.Rows.Add(row);

                dataGridView1.DataSource=table;
1

Pewnie, że zawsze będziesz miał po jednym wpisie, bo przy każdej iteracji tworzysz nowy DataTable z jednym wierszem danych.

Wyrzuć to:

DataTable table = new DataTable();
table.Columns.Add("Currency",typeof(string));
table.Columns.Add("Rate", typeof(string));

poza pętlę.

Natomiast to dataGridView1.DataSource=table; daj na końcu po zakończeniu pętli, za klamrą.

1
DataTable table = new DataTable();

table.Columns.Add("Currency", typeof(string));
table.Columns.Add("Rate", typeof(string));

XDocument.Load("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
 .Descendants()
 .Where(e => e.Attribute("currency") != null && e.Attribute("rate") != null)
 .ToList()
 .ForEach(e => table.Rows.Add(e.Attribute("currency").Value, e.Attribute("rate").Value));

dataGridView1.DataSource = table;

1 użytkowników online, w tym zalogowanych: 0, gości: 1