.net 将xml转换成DateSet

/// <summary>

/// 将XML字符串转换成DATASET

/// </summary>

/// <param name="xmlStr"></param>

/// <returns></returns>

public static DataSet ConvertToDateSetByXmlString(string xmlStr)

{

if (xmlStr.Length > 0)

{

if (xmlStr.Contains("</NewDataSet><NewDataSet>"))

{

xmlStr = xmlStr.Replace("</NewDataSet><NewDataSet>", "");

}

DataSet ds = new DataSet();

StringReader StrStream = null;

XmlTextReader Xmlrdr = null;

try

{

//读取字符串中的信息                     StrStream = new StringReader(xmlStr);

//获取StrStream中的数据                     Xmlrdr = new XmlTextReader(StrStream);

//ds获取Xmlrdr中的数据                      ds.ReadXml(Xmlrdr);

return ds;

}

catch (Exception e)

{

throw e;

}

finally

{

//释放资源                     if (Xmlrdr != null)

{                         Xmlrdr.Close();

StrStream.Close();

}

}

}

else

{

return null;

}

}

/// <summary>

/// 将XML字符串转换成DATASET

/// </summary>

/// <param name="xmlStr"></param>

/// <returns></returns>

public static DataSet CTDateSetByXmlString(string xmlStr)

{

if (xmlStr.Length > 0)

{

if (xmlStr.Contains("</NewDataSet><NewDataSet>"))

{

xmlStr = xmlStr.Replace("</NewDataSet><NewDataSet>", "</NewDataSet>,<NewDataSet>");

}

string[] strXmlArr = xmlStr.Split(',');

DataSet dsTotle = new DataSet();

for (int i = 0; i < strXmlArr.Length; i++)

{

StringReader StrStream = null;

XmlTextReader Xmlrdr = null;

DataTable dt = null;

DataSet ds = new DataSet();

try

{

//读取字符串中的信息                         StrStream = new StringReader(strXmlArr[i].ToString());

//获取StrStream中的数据                         Xmlrdr = new XmlTextReader(StrStream);

//ds获取Xmlrdr中的数据                          ds.ReadXml(Xmlrdr);

dt = ds.Tables[0];

dt.TableName = dt.TableName + i;

}

catch (Exception e)

{

throw e;

}

finally

{

//释放资源                         if (Xmlrdr != null)

{

Xmlrdr.Close();

StrStream.Close();

}

}

dsTotle.Tables.Add(dt.Copy());

}

return dsTotle;

}

else

{

return null;

}

}

XML格式

string strDtXML = @"<NewDataSet>

           <Table>

           <列名a>201411</列名a>

           <列名b>XX</列名b>

           <列名c>北京</列名c>

           </Table>

           <Table>

           <列名a>201411</列名a>

           <列名b>FF</列名b>

           <列名c>黑龙江</列名c>

           </Table>

           </NewDataSet>";

DataSet dsSet = CTDateSetByXmlString(strDtXML);

上一篇:Week2(9月19日):增加一个CodeFirst的例子来说明


下一篇:Android Processes and Threads