Wednesday, January 19, 2011

How to Create XML file in CSharp.Net

 public static String GetObjectXml<T>(T obj)
       {
           System.Xml.Serialization.XmlSerializer objxml = new System.Xml.Serialization.XmlSerializer(typeof(T));
           MemoryStream objStream = new MemoryStream();
           System.Xml.XmlTextWriter objWriter = new System.Xml.XmlTextWriter(objStream, Encoding.UTF8);
           objxml.Serialize(objWriter, obj);
           return new UTF8Encoding().GetString(((MemoryStream)objWriter.BaseStream).ToArray());
       }


Also you can do like:

           Here is the code to create xml.
            string strPath = @"C:\settings.xml";
            StringBuilder str = new StringBuilder();
            str.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> ");           
            str.Append("<Settings>");
            str.Append("<Hello>");
            str.Append("123");
            str.Append("</
Hello>");

            str.Append("<Hai>");
            str.Append("234");
            str.Append("</
Hai>");         
            
            str.Append("</Settings>");           

            try
                {
                    FileStream file = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    StreamWriter sw = new StreamWriter(file);
                    sw.Write(str);
                    sw.Close();
                }
                catch(Exception ex)
                {
                }

No comments:

Post a Comment