public void updateCartFile(List<CartObject> newCartObj)
{
bool found = false;
string cartFile = "C:\\Users\\Kiran\\Desktop\\cart.xml";
if (!File.Exists(cartFile))
{
XmlTextWriter xWriter = new XmlTextWriter(cartFile, Encoding.UTF8);
xWriter.Formatting = Formatting.Indented;
xWriter.WriteStartElement("carts");
xWriter.WriteStartElement("cart");
xWriter.WriteAttributeString("emailId", Session["emailId"].ToString());
xWriter.Close();
}
XmlDocument doc = new XmlDocument();
doc.Load(cartFile);
foreach (CartObject cartItem in newCartObj)
{
foreach (XmlNode xNode in doc.SelectNodes("carts"))
{
XmlNode cartNode = xNode.SelectSingleNode("cart");
if (cartNode.Attributes["emailId"].InnerText == Session["emailId"].ToString())
{
found = true;
XmlNode bookNode = doc.CreateElement("book");
XmlNode nameNode = doc.CreateElement("name");
nameNode.InnerText = cartItem.itemName;
XmlNode priceNode = doc.CreateElement("price");
priceNode.InnerText = cartItem.itemPrice.ToString();
XmlNode quantityNode = doc.CreateElement("quantity");
quantityNode.InnerText = "1";
bookNode.AppendChild(nameNode);
bookNode.AppendChild(priceNode);
bookNode.AppendChild(quantityNode);
cartNode.AppendChild(bookNode);
}
}
if(!found)
{
XmlNode cartNode = doc.CreateElement("cart");
cartNode.Attributes["emailId"].InnerText = Session["emailId"].ToString();
XmlNode bookNode = doc.CreateElement("book");
XmlNode nameNode = doc.CreateElement("name");
nameNode.InnerText = cartItem.itemName;
XmlNode priceNode = doc.CreateElement("price");
priceNode.InnerText = cartItem.itemPrice.ToString();
XmlNode quantityNode = doc.CreateElement("quantity");
quantityNode.InnerText = "1";
bookNode.AppendChild(nameNode);
bookNode.AppendChild(priceNode);
bookNode.AppendChild(quantityNode);
cartNode.AppendChild(bookNode);
doc.DocumentElement.AppendChild(cartNode);
}
}
doc.Save(cartFile);
}