Reputation: 59
I want to add a new node to my xml file, but also, i would like to add id value in it, but incremented by 1 from the last value. Here is my XML:
<users>
<user>
<id>1</id>
<name>Name1</name>
<surname>Surname1</surname>
<weight>78</weight>
<height>180</height>
</user>
<user>
<id>2</id>
<name>Name2</name>
<surname>Surname2</surname>
<weight>84</weight>
<height>180</height>
</user>
</users>
And here is my code so far (for adding a new node):
XmlNode node = xmlDoc.SelectSingleNode("/users/user");
XmlNode newNode = xmlDoc.ImportNode(node, true);
xmlDoc.DocumentElement.AppendChild(newNode);
xmlDoc.SelectSingleNode("users/user/id").InnerText = ; // <-- ??
xmlDoc.SelectSingleNode("users/user/name").InnerText = nameBox.Text;
xmlDoc.SelectSingleNode("users/user/surname").InnerText = surnameBox.Text;
xmlDoc.SelectSingleNode("users/user/weight").InnerText = Convert.ToString(weightUpDown.Value);
xmlDoc.SelectSingleNode("users/user/height").InnerText = Convert.ToString(heightUpDown.Value);
I am using winforms in C#, in this case get the value from the text boxes and UpDown lists. How can I do it in c#?
Upvotes: 0
Views: 8039
Reputation: 11
using the count to determine the Id may not work correctly if nodes are removed from the XML, during execution of the program.
Use Guid.NewGuid()
instead to create a unique ID
Upvotes: 1
Reputation: 101701
You can use LINQ to XML
for that.First get the current element count, then insert a new element like this:
var xDoc = XDocument.Load("path");
var count = xDoc.Descendants("user").Count();
var newUser = new XElement("user",
new XElement("id", count+1),
new XElement("name", nameBox.Text),
new XElement("surname", surnameBox.Text),
new XElement("weight", weightUpDown.Value),
new XElement("height", heightUpDown.Value));
xDoc.Root.Add(newUser);
xDoc.Save(path);
I would suggest you to get element count first (maybe in Form_load) then store it into a variable.By doing that you don't need to perform this query each time you want to add new item.You just need to increment the count.
Upvotes: 4
Reputation: 116168
You can get the max id as follows:
var maxId = xmlDoc.SelectNodes("/users/user/id")
.Cast<XmlNode>()
.Max(node => int.Parse(node.InnerText));
Upvotes: 1
Reputation: 23
I think I need some more information...
At first glance it looks like you will need to do the following:
You will be auto-populating each node with the values anyways correct?
All you will need is to add this counter variable and you should have basically what you need.
Upvotes: 0