使用c#将字符串转换为数据表

我想知道如何将此字符串转换为数据表。这个字符串是我的字符串:


"<data name=\"Footer\" xml:space=\"preserve\"> <value>Digital Number</value> </data>,<data name=\"lblDisplay\" xml:space=\"preserve\"> <value>Hien thi</value> </data>"

我创建了包含名为“名称”和“值”的 2 列的表:


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);

如何将字符串转换为DataTable?


www说
浏览 293回答 1
1回答

手掌心

您发布的字符串看起来很像 xml,但它不是有效的 xml。它需要一个根元素(并删除,逗号)。我已经更新如下:var xmlString = @"<?xml version=""1.0""?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <rootData>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <data name=""Footer"" xml:space=""preserve"">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <value>Digital Number</value>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </data>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <data name=""lblDisplay"" xml:space=""preserve"">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <value>Hien thi</value>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </data>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </rootData>";DataSetReadXml()有一个方法...提供了一种从 XML 文档中仅读取数据或将数据和模式读取到 DataSet 中的方法...知道了这一点,现在您可以创建一个DataSet并使用一个StringReader将 Xml 直接读入数据集中。var ds = new DataSet();using (var reader = new StringReader(xmlString)){&nbsp; &nbsp; ds.ReadXml(reader);}然后,您需要做的就是从 DataSet 中提取数据:Console.WriteLine($"{ds.Tables[0].Rows[0]["name"]}: {ds.Tables[0].Rows[0]["value"]}");// outputFooter: Digital Number如果你想要一个 DataTable 就这样做:&nbsp;DataTable dt = ds.Tables[0];看到这个小提琴。
打开App,查看更多内容
随时随地看视频慕课网APP