Refactor Code

  • Gravatar
    Using SqlBulkCopy Class to Insert from an XML File

    by azamsharp on 6/26/2008 3:14:59 PM
  • I wanted to insert the contents of an XML file into the database using SqlBulkCopy class. Off course I can use DataSet to fill the DataTable with the contents of the XML file but this technique loads everything in memory and hence I did not liked it. The other way to is to create a class that inherits from IDataReader and reads the XML file using XmlTextReader. Here is the GetValue method of the custom XmlDataReader class. It works great but somehow it enters one more row which is blank. If you want the complete code please visit the following URL: http://gridviewguy.com/Articles/418_HULK_UP_Your_Bulk_Copy_Operations_Using_SqlBulkCopy.aspx
  • public object GetValue(int i)
    {
    string value = String.Empty;

    try
    {
    while (_reader.Read())
    {
    if (_reader.NodeType == XmlNodeType.Element)
    {
    if (!String.IsNullOrEmpty(_reader.Name) && _columns.Contains(_reader.Name))
    {
    value = _reader.ReadElementString(_reader.Name);
    break;
    }
    }

    }
    }

    catch (Exception ex) {

    // log the exception!
    }

    return value;
    }
  • Refactor it!
Please log in to refactor the code! Login