如何将XML读入DataTable?

我在内存中的string中有一些XML,如下所示:

  EURCHF EURGBP EURJPY EURUSD  

我想把它读成DataTable 。 我是这样做的:

 DataTable dt = new DataTable(); dt.TableName = "symbols"; dt.Columns.Add("symbol"); if (!String.IsNullOrEmpty(symbols)) { dt.ReadXml(new StringReader(symbols)); } 

但是,当我检查行数时, DataTable最终会有零行。 我究竟做错了什么?

从这里: http : //www.dreamincode.net/code/snippet3186.htm

 //  /// method for reading an XML file into a DataTable ///  /// name (and path) of the XML file ///  public DataTable ReadXML(string file) { //create the DataTable that will hold the data DataTable table = new DataTable("XmlData"); try { //open the file using a Stream using(Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read)) { //create the table with the appropriate column names table.Columns.Add("Name", typeof(string)); table.Columns.Add("Power", typeof(int)); table.Columns.Add("Location", typeof(string)); //use ReadXml to read the XML stream table.ReadXml(stream); //return the results return table; } } catch (Exception ex) { return table; } } 

您可能需要查看DataTable.ReadXml方法。

编辑:如果你在内存中有xml对象,你可以直接使用ReadXml方法。 DataTable.ReadXml(MemoryStream Object);

编辑2:我做了出口。 需要以下XML Schema:

    EURCHF   EURGBP   EURJPY   

像这样:

 Dim strXmlString As String = "Table11" strXmlString += "Table22" Dim srXMLtext As System.IO.StringReader = New System.IO.StringReader(strXmlString) Dim dt As New DataTable dt.ReadXml(srXMLtext) 

其他方式:

 public DataTable ReadXML(string yourPath) { DataTable table = new DataTable("Item"); try { DataSet lstNode = new DataSet(); lstNode.ReadXml(yourPath); table = lstNode.Tables["Item"]; return table; } catch (Exception ex) { return table; } } 

使用数据集代替数据表