Saturday, October 1, 2011

Write an XML Document Programmatically C#

In this article, you will see how to read and write XML documents in Microsoft .NET using C# language.


public void writeXMLDoc(int ID, string strProductName, string strCategory, string strDescription, int intPrice)
{    
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("XML\\myFile.xml"));        
            XmlElement elmNew = xmlDoc.CreateElement("Product");


            XmlElement elmRoot = xmlDoc.DocumentElement;
            elmRoot.AppendChild(elmNew);


            elmNew = xmlDoc.CreateElement("ID");
            XmlText txtProducts = xmlDoc.CreateTextNode(ID.ToString());
            elmRoot.LastChild.AppendChild(elmNew);
            elmRoot.LastChild.LastChild.AppendChild(txtProducts);


            elmNew = xmlDoc.CreateElement("ProductName");
            txtProducts = xmlDoc.CreateTextNode(strProductName);
            elmRoot.LastChild.AppendChild(elmNew);
            elmRoot.LastChild.LastChild.AppendChild(txtProducts);


            elmNew = xmlDoc.CreateElement("Category");
            txtProducts = xmlDoc.CreateTextNode(strCategory);
            elmRoot.LastChild.AppendChild(elmNew);
            elmRoot.LastChild.LastChild.AppendChild(txtProducts);


            elmNew = xmlDoc.CreateElement("Description");
            txtProducts = xmlDoc.CreateTextNode(strDescription);
            elmRoot.LastChild.AppendChild(elmNew);
            elmRoot.LastChild.LastChild.AppendChild(txtProducts);


            elmNew = xmlDoc.CreateElement("Price");
            txtProducts = xmlDoc.CreateTextNode(intPrice.ToString());
            elmRoot.LastChild.AppendChild(elmNew);
            elmRoot.LastChild.LastChild.AppendChild(txtProducts);


            xmlDoc.Save(Server.MapPath("XML\\myFile.xml"));
}


Hope this hepls!

1 comments:

Phạm Anh Tuấn said...

interesting ;))

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews