Páginas

11/11/2010

[C#] Converter um DataTable em uma string XML

private string dataTable2XML(DataTable dataTable)
{

StringBuilder xml
= new StringBuilder();

short i;
xml.AppendLine(xmlNodeOpen(
"ITENS"));
foreach (DataRow row in dataTable.Rows)
{
xml.AppendLine(xmlNodeOpen(
"ITEM"));
i
= 0;
foreach (DataColumn column in dataTable.Columns)
{
xml.AppendLine(xmlNodeCont(column.ColumnName, row[i].ToString()));
i
++;
}
xml.AppendLine(xmlNodeClose(
"ITEM"));
}
xml.AppendLine(xmlNodeClose(
"ITENS"));
return xml.ToString();
}

private string xmlNodeOpen(string nodeName)
{
return "<" + nodeName + ">";
}

private string xmlNodeCont(string nodeName, string nodeValue)
{
return "<" + nodeName + ">" + xmlClean(nodeValue) + "</" + nodeName + ">";
}

private string xmlNodeClose(string nodeName)
{
return "</" + nodeName + ">";
}

public string xmlClean(string str)
{
//str = "<node>node'\"node\"&</ode>";
return str.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
}

Nenhum comentário: