XML file creating and reading in C#

To create an XML File from C# code side you can write down a small function that would take input parameters of the values that you want be insert in as values of an XML File.


public static bool CreateXml(string JuiceName, string CookieName, int NoOfBreadPackets,int NoOfEggs)
        {
            bool IsCreated = false;            
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(docNode);

                XmlNode MainNode = doc.CreateElement("GroceryItems");
                doc.AppendChild(MainNode);

                XmlNode Node1 = doc.CreateElement("Juice");
                string str1 = Convert.ToString(JuiceName);
                Node1.InnerXml = str1;                
                MainNode.AppendChild(Node1);


                XmlNode Node2 = doc.CreateElement("Cookie");
                string str2 = Convert.ToString(CookieName);
                Node2.InnerXml = str2;
                MainNode.AppendChild(Node2);

                XmlNode Node3 = doc.CreateElement("BreadPacket");
                Node3.InnerXml = NoOfBreadPackets;
                MainNode.AppendChild(Node3);

                XmlNode Node4 = doc.CreateElement("Eggs");
                Node4.InnerXml = NoOfEggs;
                MainNode.AppendChild(Node4);

                string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

                doc.Save(apPath + "\\AppData\\GroceryItemsTest.xml");
    IsCreated = true;
            }
            catch (Exception ex)
            {
    IsCreated = false;
            }
            finally
            {               
            }
            return IsCreated;
        }

Now lets find out how to read a particular node this file.

For that you just need to write a simple small function, where you need to pass the name of your node which will return your value for that particular node.


public string GetNodeValue(string Name)
        {
            string response = string.Empty;
            try
            {                
                System.Xml.XmlDocument doc = new XmlDocument();
                doc.Load(HttpContext.Current.Server.MapPath("/App_Data/GroceryItemsTest.xml"));
                XmlNode node = doc.SelectSingleNode("GroceryItems/" + Name);
                if (node != null)
                {
                    response = node.InnerText.ToString();                    
                }
                else {
                    response = "Requested Name Not Found.";
                }
            }
            catch (Exception ex)
            {
                response = ex.ToString();                
            }
            return response;
        }  

Comments

Popular posts from this blog

Office365