quarta-feira, 29 de julho de 2015

XML Utils C#

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml.Xsl;
using System.Xml;
using System.Text;
using System.IO;

namespace Lapuinka.Utils
{
    public class Transformer
    {

        public static String transform(String xslPath, String xml)
        {
            StringBuilder html = new StringBuilder();
            XmlWriter xmlWriter = XmlWriter.Create(html);

            StringReader stringReader = new StringReader(xml);
            XmlReader xmlReader = XmlReader.Create(stringReader);

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(xslPath);
            transform.Transform(xmlReader, xmlWriter);

            return html.ToString();
        }

        public static string SerializeToXMLString(object ObjectToSerialize)
        {
            MemoryStream mem = new MemoryStream();
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(ObjectToSerialize.GetType());
            ser.Serialize(mem, ObjectToSerialize);
            ASCIIEncoding ascii = new ASCIIEncoding();
            return ascii.GetString(mem.ToArray());
        }

        public static object DeSerializeFromXMLString(System.Type TypeToDeserialize, string xmlString)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString);
            MemoryStream mem = new MemoryStream(bytes);
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(TypeToDeserialize);
            return ser.Deserialize(mem);
        }


    }
}


Postar um comentário