0

So I've been working on a project and I've hit a snag. I need to read employee data from XML files, then display that data in a ListBox.

NB: "tempFullName" is an empty string assigned at the start of the script. It is never reset to null.

void NewDateItemLoad(object sender, EventArgs e)
    {

        string path = Application.StartupPath.ToString() + "\\Users";
        int fCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length;
        for(int i = 0;i<fCount;i++)
        {
            String[] filePaths = Directory.GetFiles(Application.StartupPath + "\\Users\\");
            XmlDocument xmlFile =new XmlDocument();
            xmlFile.Load(filePaths[i]);

            foreach(XmlNode node in xmlFile.SelectNodes("//Account"))
            {
                XmlNode nodeFirstName = node.SelectSingleNode("FirstName");
                XmlNode nodeLastName = node.SelectSingleNode("LastName");

                if(nodeFirstName.Value != "" && nodeLastName.Value != ""){
                    tempFullName = nodeFirstName.Value + nodeLastName.Value;
                }

            }


            lstWorkers.Items.Add(tempFullName);
            lstWorkers.Items.Add("-------------------"); //Temporary Divide


        }
    }

Each employee has their own XML file because I set my program to use that format because I found it easier before I understood correctly how to interact with XML files. I use a similar process for searching through login details and that works perfectly fine, sadly the names do not show in the listbox.

http://puu.sh/g5cjK/7132fe251f.png This is the result of the code. http://puu.sh/g5cWQ/254ecb4041.png An example of the XML files I'm using.

If anyone could help make the employee names show correctly, or point out where I've gone wrong that'd be greatly appreciated.

Sky
  • 83
  • 1
  • 7

2 Answers2

1

The names are independent text nodes within the element so rather than reading .Value

if (nodeFirstName.InnerText != "" && nodeLastName.InnerText != "")

If there are multiple elements, you need to add to the list within the loop else you will always end up with the last one.

You may like to stuff all the XML in a single file.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

If you want something fully automated and that will work simply with no heavy logic, I suggest to go with xmlSerialiser. Go to that link for more informations.

Community
  • 1
  • 1
Fjodr
  • 919
  • 13
  • 32