简体   繁体   中英

Reading from multiple XML files and displaying data in a ListBox issue

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM