1、添加新节点前进行判断看是否已存在相同的属性值,若存在进行更新,不存在则进行添加操作。
protected bool AddPizza() { //初始化id int newId; string filePath = HttpContext.Current.Server.MapPath("XMLFile.xml"); //创建XML文件对象的实例doc XmlDocument doc = new XmlDocument(); //加载XML文件 doc.Load(filePath); //获取结点Pizza下的所有子结点 XmlNodeList nodeList = doc.SelectSingleNode("Pizza").ChildNodes; bool isExist = true; foreach (XmlElement xe in nodeList) { isExist = xe.Attributes["size"].Value == tbPizzaSize.Text; if (isExist) { xe.SetAttribute("price", tbPizzaPrice.Text); doc.Save(filePath); } } if (!isExist) { if (nodeList.Count > 0) { //查找最后一个结点的id newId = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("/Pizza/Pizzas[last()]").Attributes["id"].Value) + 1; //创建一个新的xml元素 XmlElement Pizzas = doc.CreateElement("Pizzas"); //创建xml属性 XmlAttribute id = doc.CreateAttribute("id"); XmlAttribute size = doc.CreateAttribute("size"); XmlAttribute price = doc.CreateAttribute("price"); //给xml属性赋值 id.Value = newId.ToString(); size.Value = tbPizzaSize.Text; price.Value = tbPizzaPrice.Text; //给结点赋值 Pizzas.InnerText = tbPizzaName.Text; //把属性值添加到元素结点里 Pizzas.Attributes.Append(id); Pizzas.Attributes.Append(size); Pizzas.Attributes.Append(price); //把元素结点添加到XMl文件里 doc.DocumentElement.AppendChild(Pizzas); //保存XML文件 doc.Save(filePath); } else { newId = 1; } } return true; }