0

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much for your help, i solved it with your ideal, my string acctually is from a resource file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.