简体   繁体   English

C#如何获取XML文件的所有用户

[英]C# how can i get all users of the XML file

I have created an xml file and there are stored my user. 我已经创建了一个xml文件,并且存储了我的用户。 The problem, I only ever get the first one out. 问题是,我只得到第一个。 How do I manage to get all users of the XML file displayed? 如何管理所有显示XML文件的用户?

        private void button1_Click(object sender, EventArgs e)
    {
        string path = "C:\\temp\\Accounts.xml";

        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        XmlElement root = doc.CreateElement("Login");
        XmlElement user = doc.CreateElement("user");
        user.InnerText = textBox1.Text;


        root.AppendChild(user);
        doc.DocumentElement.AppendChild(root);
        doc.Save(path);
        MessageBox.Show("Created SuccesFully!");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        XmlDocument xdoc = new XmlDocument();
        xdoc.Load("C:\\temp\\Accounts.xml");

        foreach (XmlNode person in xdoc.SelectNodes("/Login"))
        {
            MessageBox.Show(person["user"].InnerText);
        }

    }

I'm not sure what wasn't working for you, but this works for me. 我不确定什么对您不起作用,但这对我有用。 I am using //Login as the path selector. 我正在使用//Login作为路径选择器。 Ensure that your XML file actually has multiple users. 确保您的XML文件实际上有多个用户。

void Main()
{
    //Create();
    View();

    // Output:
    // User1
    // User2
}

private void Create()
{
    string path = "C:\\Code\\Sandbox\\Accounts.xml";
    XmlDocument doc = new XmlDocument();
    doc.Load(path);
    XmlElement root = doc.CreateElement("Login");
    XmlElement user = doc.CreateElement("user");
    user.InnerText = "User2";
    root.AppendChild(user);
    doc.DocumentElement.AppendChild(root);
    doc.Save(path);
    Console.WriteLine("Created SuccesFully!");
}

private void View()
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load("C:\\Code\\Sandbox\\Accounts.xml");
    foreach (XmlNode person in xdoc.SelectNodes("//Login"))
    {
        Console.WriteLine(person["user"].InnerText);
    }
}

Here is the generated XML. 这是生成的XML。 I inserted a root Logins element. 我插入了一个根Logins元素。

<Logins>
  <Login>
    <user>User1</user>
  </Login>
  <Login>
    <user>User2</user>
  </Login>
</Logins>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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