I want to know how to convert this string to datatable. This string is my string:
"<data name=\"Footer\" xml:space=\"preserve\"> <value>Digital Number</value> </data>,<data name=\"lblDisplay\" xml:space=\"preserve\"> <value>Hien thi</value> </data>"
I created table with 2 column named "Name" and "Value":
DataTable tbl = new DataTable();
DataColumn column;
DataRow row;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Name";
tbl.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Value";
tbl.Columns.Add(column);
How can I convert the string to DataTable
?
The string you posted looks a lot like xml, but it is not valid xml. It needs a root element (and remove the ,
comma). I've updated below:
var xmlString = @"<?xml version=""1.0""?>
<rootData>
<data name=""Footer"" xml:space=""preserve"">
<value>Digital Number</value>
</data>
<data name=""lblDisplay"" xml:space=""preserve"">
<value>Hien thi</value>
</data>
</rootData>";
DataSet
has a method ReadXml()
which
... provides a way to read either data only, or both data and schema into a DataSet from an XML document...
Knowing that, now you can create a DataSet
and use a StringReader
to read the Xml straight into the DataSet.
var ds = new DataSet();
using (var reader = new StringReader(xmlString))
{
ds.ReadXml(reader);
}
Then, all you need to do is extract the data from the DataSet:
Console.WriteLine($"{ds.Tables[0].Rows[0]["name"]}: {ds.Tables[0].Rows[0]["value"]}");
// output
Footer: Digital Number
If you want a DataTable just do:
DataTable dt = ds.Tables[0];
See this fiddle .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.