0

I need help creating xml file with C#

ok lets say I have the following users.xml file that contains the following

<Users>

</Users>

After executing the C# code below

 public void addUser()
        {
            string filePaths = "users.xml";
            XmlDocument xmlDoc = new XmlDocument();
            string user = textBox2.Text; // USER INPUT

            if (File.Exists(filePaths))
            {
                xmlDoc.Load(filePaths);

                XmlElement elmRoot = xmlDoc.DocumentElement; 
                XmlElement elmNew = xmlDoc.CreateElement("User");
                elmRoot.AppendChild(elmNew);

                elmRoot = xmlDoc.DocumentElement;
                elmNew = xmlDoc.CreateElement("Name");

                XmlText CreateUserText = xmlDoc.CreateTextNode(user);

                elmRoot.LastChild.AppendChild(elmNew);
                elmRoot.LastChild.LastChild.AppendChild(CreateUserText);//8
                xmlDoc.Save(filePaths);
            }

        }

I get the following xml file

<Users>
  <User>  <!-- Generated by C# code above -->
    <Name>Eric</Name> <!-- Generated by C# code above -->
  </User> <!-- Generated by C# code above -->
</Users>

I can keep adding users, so for example if i executed again with another name in textBox2. it would produce

 <Users>
      <User>  <!-- Generated by C# code above -->
        <Name>Eric</Name> <!-- Generated by C# code above -->
      </User> <!-- Generated by C# code above -->
      <User>  <!-- Generated by C# code above -->
        <Name>Michelle</Name> <!-- Generated by C# code above -->
      </User> <!-- Generated by C# code above -->
    </Users>

What I am really asking is how would i modify my C# code so that no repeated names are added to the xml file.For example, if i tried to add Eric again in my C# program, users.xml file should not add the name Eric because the name Eric already exist.

Thanks for your help, in advance.

2
Contributors
1
Reply
3
Views
4 Years
Discussion Span
Last Post by Mike Askew
0

You would need to use an XPath query to see if anything returns under the given name, then you can proceed from there with decision making logic

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.