If you use
LINQ
with
XDocument
and
XElement
I think it is easier for you.
XElement xeTable = new XElement("Table");
XElement xeProducts = new XElement("Product");
createNode("5", "Product 5", "5000", xeProducts);
createNode("6", "Product 6", "5000", xeProducts);
createNode("7", "Product 7", "5000", xeProducts);
createNode("8", "Product 8", "5000", xeProducts);
xeTable.Add(xeProducts);
XDocument xdoc = new XDocument();
xdoc.Declaration = new XDeclaration("1.0", "utf8", "yes");
xdoc.Add(xeTable);
xdoc.Save(@"XMLFile1.xml");
private void createNode(string pID, string pName, string pPrice, XElement xeProducts)
{
XElement xeProduct = new XElement("Product");
xeProduct.Add(new XElement("Product_id", pID));
xeProduct.Add(new XElement("Product_name", pName));
xeProduct.Add(new XElement("Product_price", pPrice));
xeProducts.Add(xeProduct);
}
Resulting XML
<Products>
<Product>
<Product_id>5</Product_id>
<Product_name>Product 5</Product_name>
<Product_price>5000</Product_price>
</Product>
<Product>
<Product_id>6</Product_id>
<Product_name>Product 6</Product_name>
<Product_price>5000</Product_price>
</Product>
<Product>
<Product_id>7</Product_id>
<Product_name>Product 7</Product_name>
<Product_price>5000</Product_price>
</Product>
<Product>
<Product_id>8</Product_id>
<Product_name>Product 8</Product_name>
<Product_price>5000</Product_price>
</Product>
</Products>
Example of how to read the file:
XDocument xdoc2 = XDocument.Load(@"XMLFile1.xml");
XElement xeProducts2 = xdoc2.Root.Element("Products");
XElement xeProduct7 = xeProducts.Elements("Product").
Where(x => x.Element("Product_id").Value == "7").FirstOrDefault();
Result of the query:
<Product>
<Product_id>7</Product_id>
<Product_name>Product 7</Product_name>
<Product_price>5000</Product_price>
</Product>
Access the members
string productName = xeProduct7.Element("Product_name").Value;
Append
XDocument xdoc = XDocument.Load(@"XMLFile1.xml");
XElement xeProducts = xdoc.Root.Element("Products");
createNode("10", "Product 10", "10000", xeProducts);
xdoc.Save(@"XMLFile1.xml");
Delete
XDocument xdoc = XDocument.Load(@"XMLFile1.xml");
XElement xeProducts = xdoc.Root.Element("Products");
XElement xeProduct7 = xeProducts.Elements("Product").
Where(x => x.Element("Product_id").Value == "7").FirstOrDefault();
xeProduct7.Remove();
xdoc.Save(@"XMLFile1.xml");
From here on you need to use your own brain la.