Skip to content

Instantly share code, notes, and snippets.

@renatoeufe
Created May 23, 2012 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoeufe/2777415 to your computer and use it in GitHub Desktop.
Save renatoeufe/2777415 to your computer and use it in GitHub Desktop.
Convert datatable rows into a list of XML strings
using System.Data;
namespace QueryToXml.Lib.Extensions
{
public static class ExtensionMethods
{
public static string[] ColumnNames(this DataTable dataTable)
{
var columns = new string[dataTable.Columns.Count];
for (var c = 0; c < dataTable.Columns.Count; c++)
columns[c] = dataTable.Columns[c].ColumnName;
return columns;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using QueryToXml.Lib.Extensions;
namespace QueryToXml.Lib
{
public class Parser : IDisposable
{
public ICollection<string> Items { get; private set; }
public DataTable Source { get; private set; }
private string[] Columns { get; set; }
public Parser(DataTable source)
{
if (string.IsNullOrEmpty(source.TableName))
throw new InvalidDataException("No table name found on data table");
Source = source;
Columns = Source.ColumnNames();
}
public ICollection<string> Parse()
{
Items = new List<string>();
if (Columns.Length == 0)
throw new InvalidDataException("No columns found");
foreach (DataRow row in Source.Rows)
{
var sb = new StringBuilder();
sb.AppendLine(string.Concat("<", Source.TableName, ">"));
for (var c = 0; c < Columns.Length; c++)
sb.AppendLine(string.Format("<{0}>{1}</{0}>", Columns[c], row[c]));
sb.AppendLine(string.Concat("</", Source.TableName, ">"));
Items.Add(sb.ToString());
}
return Items;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment