C # Foreach XML node

I am trying to add all nodes to an XML file in a listView, and I am doing something wrong, but I can’t figure it out for life even after looking at the examples. This is an XML fragment:

<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 is 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 is much appreciated, as always.

EDIT: To clarify, I get a NullReferenceException in

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

And I know that the list is missing, I haven't done this bit yet :)

+5
source share
3 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();

It looks better, and since you did not say what exactly is wrong with your code, this is about all I can do.

Update: Just tested this and it fixes your exception.

+3
source

XML . NullReferenceException , XML, , .

string filename = download.Element("filename") == null ? 
    String.Empty : download.Element("filename").Value;

, filename. , , .

+2
void LoadSlots()
{
  XmlDocument doc = new XmlDocument();
  doc.Load(Environment.CurrentDirectory + "\\queue.xml");

  XmlNodeList nodes = doc.SelectNodes("//queue/slots/slot");

  foreach (XmlNode node in nodes)
  {
    string filename = node.Attributes["filename"].InnerText;
    string size = node.Attributes["size"].InnerText;
    string status = node.Attributes["status"].InnerText;
    _slots.Add(filename, size, status);
  }
}
+1
source

All Articles