0

I'm trying to load xml data in to my ListView control, but not working correctly.

The XML content is:

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee ID="1">
    <Name>Numeri</Name>
  </Employee>
  <Employee ID="5">
    <Name>husu</Name>
  </Employee>
  <Employee ID="6">
    <Name>sebri</Name>
  </Employee>
</Employees>

This is what I have tried to load the data:

        private void btn_load_Click(object sender, EventArgs e)
        {
            XDocument doc = XDocument.Load(Application.StartupPath + "/Employees.xml");

            foreach (var dm in doc.Descendants("Employee"))
            {
                ListViewItem item = new ListViewItem(new string[]
                {
                    dm.XAttribute("ID").Value,
                    dm.XElement("Name").Value
                });
                listView1.Items.Add(item);
            }

It is preferable if the help is provided using XML-Linq.

Thanks in Advance.

usminuru
  • 335
  • 4
  • 8
  • 19
  • Related: [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül May 27 '15 at 11:40
  • are u getting data from XML file. Have you checked? – user786 May 27 '15 at 11:41
  • 1
    You may be getting `doc` as null. – Mairaj Ahmad May 27 '15 at 11:42
  • try to use "var dm in doc.Descendants("Employee").Nodes()" – PaulShovan May 27 '15 at 11:48
  • Your code should've worked provided that the actual XML is exactly the same as you posted here and it successfully loaded to `XDocument`. I'd suggest you to debug and find out which variable was `null`, or follow recommended steps in the link provided by SonerGonul above to diagnose the problem (for those who confused how this Q relates to NRE, see revision history) – har07 May 27 '15 at 12:08
  • 1
    Thanks in Advance. Yes debugging is the problem. I cleaned and re Dubug and now it works. – usminuru May 27 '15 at 12:26

1 Answers1

1

Could you try doing something as like,

XDocument doc = XDocument.Load(Application.StartupPath + "/Employees.xml");
doc.Descendants("Employee").ToList()
   .ForEach(x => listView1.Items.Add(
                 new ListViewItem(
                 new string[] { x.Attribute("ID").Value, x.Element("Name").Value }))
           );

Hope this helps...

Vanest
  • 906
  • 5
  • 14