Created
May 23, 2012 19:59
-
-
Save renatoeufe/2777415 to your computer and use it in GitHub Desktop.
Convert datatable rows into a list of XML strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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