简体   繁体   中英

C# XML - can't read XML file?

I am trying to read a whole xml file loaded in doc. And I'm trying to iterate through each node and have a comparison with the textboxes to see if their account exists

Sorry for not being to in depth, its my first post, I hope these image will help: just to note, the source code worked perfectly in a console application, however doesn't in a Windows form application but when I click login button nothing seems to happen, but works in console application but not this, any ideas?

Source code:

源代码

Xml I'm reading from:

xml文件

Source code not in an image:

private void btnLogin_Click(object sender, EventArgs e)
{
        string User = txtUserName.Text;
        string pass = txtPassword.Text;

        XmlDocument Doc = new XmlDocument();
        Doc.Load("login.xml");

        //iterating through each node to use for comparison for the textboxes

        foreach (XmlNode CurrentNode in Doc.SelectNodes("accounts/user"))
        {
            string username = CurrentNode.SelectSingleNode("username").InnerText;
            string password = CurrentNode.SelectSingleNode("password").InnerText;



            if (txtUserName.Text == username && txtPassword.Text == password)
            {
                MessageBox.Show("Account exists");
            }
            else 
            {
                MessageBox.Show("does not exist");
            }


        }

Lets do a small refactoring and introduce special function, that checks username/password

static bool CheckLogin(string path, string username, string pwd)
{
return XDocument.Load(path).Root
.Elements("user")
.Any(x=>x.Element("username").Value==username && x.Element("password").Value==pwd);
}

而不是提供代码作为login.xml,而是尝试提供存在xml的完整路径。

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