首页 > 代码库 > XML TO DataSet TO DataTable 相互转换

XML TO DataSet TO DataTable 相互转换

 1       //遍历XML 获得 DataSet
//XmlTextReader
static void Main(string[] args) 2 { 3 string xmlData = http://www.mamicode.com/@"D:\study\XMLtest\XMLtest\bin\Debug\bookstore.xml"; 4 DataSet t = ConvertXMLToDataSet(xmlData); 5 Console.WriteLine(t); 6 7 } 8 9 private static DataSet ConvertXMLToDataSet(string xmlFile)10 {11 StringReader stream = null;12 XmlTextReader reader = null;13 try14 {15 XmlDocument xmld = new XmlDocument();16 xmld.Load(xmlFile);17 DataSet xmlDS = new DataSet();18 stream = new StringReader(xmld.InnerXml);19 reader = new XmlTextReader(stream);20 xmlDS.ReadXml(reader);21 return xmlDS;22 //DataSet xmlDS = new DataSet();23 //stream = new StringReader(xmlData);24 //reader = new XmlTextReader(stream);25 //xmlDS.ReadXml(reader, XmlReadMode.ReadSchema);26 //return xmlDS;27 }28 catch (Exception ex)29 {30 string strTest = ex.Message;31 return null;32 }33 finally34 {35 if (reader != null)36 reader.Close();37 }38 }

 经过调试

 

 如何把 DataSet 转换成 DataTable  *** 注意,我这里的xml文件节点相对混乱,这样读取出来在Dataset中 有三个DataTable 然后怎么把DataTable 怎么给分离开来!

 

XML :

 1 <?xml version="1.0" encoding="utf-8"?> 2 <books> 3   <book genre="update知鸟" ISBN="2-3631-4"> 4     <title name="csTitle属性"> 5           <ti>属性值</ti> 6           <ti>属性值</ti> 7           <ti> 8         9     <title>CS从入门到精通</title>10     <author>izhiniao捷</author>11     <price>58.3</price>12 13 </ti>14     </title>15     <author>izhiniao捷</author>16     <price>58.3</price>17   </book>18   <book genre="知鸟" ISBN="2-3631-4">19     <title>CS从入门到精通</title>20     <author>izhiniao</author>21     <price>58.3</price>22   </book>23 </books>
XML

 

  

 

DataSet 转换成 DataTable:

1           List<DataTable> lTb = new List<DataTable>();2             for (int i = 0; i < tttt.Tables.Count; i++)//主要就是这里的循环  3             {4                 lTb.Add(tttt.Tables[i]);5             }

 

XML TO DataSet TO DataTable 相互转换