第1种:
//通过传入的特定XML字符串,通过 ReadXml函数读取到DataSet中。
protected static DataSet GetDataSetByXml(string xmlData) { try { DataSet ds = new DataSet(); using (StringReader xmlSR = new StringReader(xmlData)) { ds.ReadXml(xmlSR, XmlReadMode.InferTypedSchema); //忽视任何内联架构,从数据推断出强类型架构并加载数据 if (ds.Tables.Count > 0) { return ds; } } return null; } catch (Exception) { return null; } }
第2种:
/// 通过传入的xml文件路径(含文件名),将格式化的Xml文件自动读取转换为DataSet。
public static DataSet ConvertXMLFileToDataSet(string xmlFile) { StringReader stream = null; XmlTextReader reader = null; try { XmlDocument xmld = new XmlDocument(); xmld.Load(xmlFile); DataSet xmlDS = new DataSet(); stream = new StringReader(xmld.InnerXml); //从stream装载到XmlTextReader reader = new XmlTextReader(stream); xmlDS.ReadXml(reader); //xmlDS.ReadXml(xmlFile); return xmlDS; } catch (System.Exception ex) { throw ex; } finally { if (reader != null) reader.Close(); } }