I have
- an old WCF SOAP service from my server,
- an .NET Framework application.
- an .NET Framework library.
I want to upgrade my library first to netstandard2.0.
Everything works well, i can regenerate WCF Client files.
However, DataTable
have changed to ...TableResult
with XmlElement
.
So, i know how to change XmlElement
to DataTable
, but how do I change DataTable
to XmlElement
?
public static class Transform
{
public static DataTable ToDataTable(XmlElement xmlElement)
{
using var reader = new XmlNodeReader(xmlElement);
var datatable = new DataTable();
datatable.ReadXml(reader);
return datatable;
}
public static XmlElement ToXmlElement(DataTable datatable)
{
throw new NotImplementedException();
}
}
CodePudding user response:
You have to use GroupBy
to group the rows, then select the parts you want into XElements
.
Here is an example:
var xml = new XElement(table.TableName, table.Rows.Cast<DataRow>()
.GroupBy(row => (string)row[0])
.Select(g =>
new XElement(table.Columns[0].ColumnName,
new XElement("label", g.Key),
g.GroupBy(row => (string)row[1])
.Select(g1 =>
new XElement(table.Columns[1].ColumnName,
new XElement("label", g1.Key),
new XElement(table.Columns[2].ColumnName,
g1.Select(row =>
new XElement("label", (string)row[2])
)
)
)
)
)
)
)
or you can use dataset
DataSet ds = new DataSet();
ds.Tables.Add(table);
XmlDocument XMLDoc = new XmlDocument();
Console.WriteLine(ds.GetXml().ToString());
// In your case:
return XMLDoc.DocumentElement;
CodePudding user response:
You may use ds.Write.xml
, this will have a Stream to put the output into. If you need it, try the method below:
public static class Extensions
{
public static string ToXml(this DataSet ds)
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(DataSet));
xmlSerializer.Serialize(streamWriter, ds);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
}
}
USAGE:
var xmlString = ds.ToXml();
Response.Write(ds.ToXml());
And you can check the docs for help.