Wednesday, May 29, 2013

XmlSerializer to Serialize Class to Xml and Bulk Load Data

you can generally store XML in a SQL Server table using normal CRUD procs.  The example below uses an XmlDocument as the source but XML from any source may be used. 
CREATE TABLE dbo.XMLTable(
  XMLTableID int NOT NULL IDENTITY(1, 1) CONSTRAINT PK_XMLTable PRIMARY KEY
  ,XMLColumn xml
 );
GO

CREATE PROC dbo.InsertXML
 @XmlParameter XML
AS
INSERT INTO dbo.XMLTable (XMLColumn) VALUES(@XmlParameter);
SELECT CAST(SCOPE_IDENTITY() AS int) AS XMLTableID;
GO
var xmlObject = new XmlDocument();
xmlObject.LoadXml("<Root><Clild>child text</Clild></Root>");
var connection = new SqlConnection(@"Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=SSPI");
connection.Open();
var command = new SqlCommand("dbo.InsertXML", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@XMLParameter", SqlDbType.Xml);
command.Parameters["@XMLParameter"].Value = xmlObject.OuterXml;
int XmlTableID = (int)command.ExecuteScalar();
connection.Close();

OR=================================================================
http://www.nullskull.com/articles/system.xml.xmlserialization.asp

private bool SerializeObject<TEntity>(TEntity obj, string xmlFilePath)
        {
            string path = xmlFilePath + ".xml";
            XmlSerializer serializer = new XmlSerializer(typeof(TEntity));
            // Create an XmlTextWriter using a FileStream.
            Stream fs = new FileStream(path, FileMode.Create);
            XmlWriter writer = new XmlTextWriter(fs, Encoding.Unicode);
            // Serialize using the XmlTextWriter.
            serializer.Serialize(writer, obj);
 
            writer.Flush();
            writer.Close();
            return true;
        }

No comments:

Post a Comment