Given the local xml file:
<products>
<product id="p1">
<name>Delta</name>
<price>800</price>
<stock>4</stock>
<country>Denmark</country>
</product>
<product id="p2">
<name>Golf</name>
<price>1000</price>
<stock>5</stock>
<country>Germany</country>
</product>
<product id="p3">
<name>Alfa</name>
<price>1200</price>
<stock>19</stock>
<country>Germany</country>
</product>
<product id="p4">
<name>Foxtrot</name>
<price>1500</price>
<stock>5</stock>
<country>Australia</country>
</product>
<product id="p5">
<name>Tango</name>
<price>1225</price>
<stock>3</stock>
<country>Japan</country>
</product>
</products>
I have attempted to replace the price element in product node 'p1' as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System;
using System.Xml.XPath;
using System.Xml.Linq;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"products.xml");
Console.WriteLine("\n\nDisplay the initial XML...");
xmlDoc.Save(Console.Out);
//Create an XmlNamespaceManager for resolving namespaces.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("products", "product");
// replace the node with a new one
//Select the profile node with the matching attribute value.
XmlNode product;
XmlElement root = xmlDoc.DocumentElement;
product = root.SelectSingleNode("descendant::product[id='p1']", nsmgr);
//Create a new price element.
XmlElement oldElem = xmlDoc.CreateElement("price");
oldElem.InnerText = "800";
//Create a new price element.
XmlElement newElem = xmlDoc.CreateElement("price");
newElem.InnerText = "125";
//Replace the price element.
root.ReplaceChild(newElem, root.FirstChild);
Console.WriteLine("\n\nDisplay the modified XML...");
xmlDoc.Save(Console.Out);
// save the document with the revised node
xmlDoc.Save(@"products2.xml");
Problem is that the new node (price) element is simply added to the product p1 node which when saved to disk drops all of p1. What am I doing wrong?