Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Foreach XML node

Tags:

c#

.net

xml

I'm trying to add all the nodes in an XML file into a listView, and I'm doing something wrong but I can't for the life of me figure it out even after looking at a load of examples. This is the XML snippet:

<queue>
<slots>
<slot>
<status>Downloading</status>
<filename>file1</filename>
<size>1 GB</size>
</slot>
<slot>
<status>Downloading</status>
<filename>file2</filename>
<size>2 GB</size>
</slot>
</slots>
</queue>

And here's the code:

        XDocument xDoc = XDocument.Load(xmlFilePath);

        List<Download> list = new List<Download>();

        foreach (var download in xDoc.Descendants("slots"))
        {
            string filename = download.Element("filename").Value;
            string size = download.Element("size").Value;
            string status = download.Element("status").Value;
            list.Add(new Download { Filename = filename, Size = size, Status = status });              
        }

Any help greatly appreciated as always.

EDIT: To clarify, I'm getting a NullReferenceException on

string filename = download.Element("filename").Value;

And i know the listview is missing, I've not done that bit yet :)

like image 809
JoeBeez Avatar asked Aug 09 '10 15:08

JoeBeez


1 Answers

var list = (from download in xDoc.Descendats("slot")
            select new Download
                    {
                        Filename = (string) download.Element("filename"),
                        Size = (string) download.Element("size"),
                        Status = (string) download.Element("status")
                    }).ToList();

This looks nicer, and since you didn't say what exactly is wrong with your code, it's about all I can do.

Update: just tested this, and it fixes your exception.

like image 108
Necros Avatar answered Sep 23 '22 13:09

Necros