terça-feira, 21 de julho de 2015

XmlUtil

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization;
namespace Lapuinka.Xml
{
    #region  XmlUtil
    ///
    /// Xml Util
    ///
       public class XmlUtil{
             public XmlUtil(){}

             ///
             /// Converts an object to an xml string.
             ///
             /// Object wanted to be converted to xml string
             /// Xml string of the object
            
             public static string ToXml(Object objToXml,bool includeNameSpace)
             {
                    StreamWriter stWriter=null;
                    XmlSerializer xmlSerializer;
                    string buffer;
                    try {
                           xmlSerializer = new XmlSerializer(objToXml.GetType());
                           MemoryStream memStream = new MemoryStream();
                           stWriter = new StreamWriter(memStream);
                           if (!includeNameSpace){
                                  System.Xml.Serialization.XmlSerializerNamespaces xs= new XmlSerializerNamespaces();
                                  xs.Add("","");
                                  xmlSerializer.Serialize(stWriter, objToXml,xs);
                           }
                           else{
                                  xmlSerializer.Serialize(stWriter, objToXml);                             
                           }
                           buffer = Encoding.ASCII.GetString(memStream.GetBuffer());
                    }
                    catch(Exception Ex){
                           throw Ex;
                    }
                    finally {
                           if(stWriter!=null) stWriter.Close();
                    }
                    return buffer;
             }
        public static string GetFileName(string action, string preFix)
        {
            int startIndex = action.LastIndexOf("/") + 1;
            action = action.Substring(startIndex, action.Length - startIndex).Replace(":", "_").Replace("/", "_").Replace("?", "_").Replace(" ", "_");
            return (preFix + "_" + action + "_" + Guid.NewGuid().ToString() + ".xml");
        }
             ///
             /// Serializes a given object to the file given with the path
             ///
             /// Object wanted to be serialized to the file
             /// Path of the file        
             public static  void ToXml(Object objToXml,string filePath,bool includeNameSpace) {
                    StreamWriter stWriter=null;
                    XmlSerializer xmlSerializer;
                    try {
                           xmlSerializer = new XmlSerializer(objToXml.GetType());
                           stWriter = new StreamWriter(filePath);
                           if (!includeNameSpace){
                                  System.Xml.Serialization.XmlSerializerNamespaces xs= new XmlSerializerNamespaces();
                                  xs.Add("","");//To remove namespace and any other inline information tag
                                  xmlSerializer.Serialize(stWriter, objToXml,xs);
                           }
                           else{
                                  xmlSerializer.Serialize(stWriter, objToXml);
                           }
                    }
                    catch(Exception exception){
                           throw exception;
                    }
                    finally {
                           if(stWriter!=null) stWriter.Close();
                    }                  
             }     

             ///
             /// Serializes a given object to the file given with the path
             ///
             /// Object wanted to be serialized to the file
             /// Includes the line if it is true, otherwise start doucment line is excluded from the exported xml.
             /// Path of the file        
             public static  void ToXml(Object objToXml,string filePath,bool includeNameSpace,bool includeStartDocument) {
                    SpecialXmlWriter stWriter=null;
                    XmlSerializer xmlSerializer;
                    try {
                           xmlSerializer = new XmlSerializer(objToXml.GetType());
                           stWriter = new SpecialXmlWriter(filePath,null,includeStartDocument);
                           System.Xml.Serialization.XmlSerializerNamespaces xs= new XmlSerializerNamespaces();
                           xs.Add("","");//To remove namespace and any other inline information tag
                           xmlSerializer.Serialize(stWriter, objToXml,xs);
                    }
                    catch(Exception Ex) {
                           throw Ex;
                    }
                    finally {
                           if(stWriter!=null) stWriter.Close();
                    }                  
             }     

             ///
             /// Deserializes the object given with the type from the given string
             ///
             /// String containing the serialized xml form of the object
             /// Type of the object to be deserialized
             /// Deserialized object
             public static object XmlTo(string xmlString,Type type) {
                    XmlSerializer xmlSerializer;
                    MemoryStream memStream=null;
                    try {
                           xmlSerializer = new XmlSerializer(type);
                           byte[] bytes=new byte[xmlString.Length];
                           Encoding.ASCII.GetBytes(xmlString,0,xmlString.Length,bytes,0);
                           memStream = new MemoryStream(bytes);                                            
                           object objectFromXml= xmlSerializer.Deserialize(memStream);                     
                           return objectFromXml;
                    }                  
                    catch(Exception Ex) {
                           throw Ex;
                    }
                    finally {                        
                           if(memStream!=null) memStream.Close();
                    }                  
             }     

             ///
             /// Deserializes the object given with the type from the given string
             ///
             /// String containing the serialized xml form of the object
             /// Type of the object to be deserialized
             /// Deserialized object
             public static object XmlToFromFile(string filePath,Type type) {
                    XmlSerializer xmlSerializer;
                    FileStream fileStream=null;
                    try {
                           xmlSerializer = new XmlSerializer(type);
                           fileStream = new FileStream(filePath,FileMode.Open,FileAccess.Read);
                           object objectFromXml= xmlSerializer.Deserialize(fileStream );                         
                           return objectFromXml;
                    }                  
                    catch(Exception Ex) {
                           throw Ex;
                    }
                    finally {                        
                           if(fileStream!=null) fileStream.Close();
                    }                  
             }     
    }
       ///
       /// This class can be used to implement special affects while producing xml documents.
       /// At the moment it is only used for excluding the xml start line( )
       ///
       public class SpecialXmlWriter:XmlTextWriter
       {
             bool m_includeStartDocument=true;
             public SpecialXmlWriter(TextWriter tw,bool includeStartDocument):base(tw) {
                    m_includeStartDocument=includeStartDocument;  
             }           
             public SpecialXmlWriter(Stream sw,Encoding encoding,bool includeStartDocument):base(sw,null) {
                    m_includeStartDocument=includeStartDocument;
             }
             public SpecialXmlWriter(string filePath,Encoding encoding,bool includeStartDocument):base(filePath,null) {
                    m_includeStartDocument=includeStartDocument;
             }
             public override void WriteStartDocument() {
                    if (m_includeStartDocument) {
                           base.WriteStartDocument();
                    }
             }
    }
    #endregion
}



Postar um comentário