c# 读取xml到dataset中

时间:2024-03-05 06:57:36

1、转换函数

private DataSet readXML(string fileName)
        {
            DataSet ds = new DataSet();
            if (System.IO.File.Exists(fileName))
            {
                string[] endStrArray = new string[] { "</XML中结束符号>", "</XML中结束符号>" };
                string xmlText = System.IO.File.ReadAllText(fileName, Encoding.Default);                      
                foreach(string endStr in endStrArray)
                {
                    int pos1 = xmlText.LastIndexOf(endStr);
                    if(pos1 > 0)
                    {
                        int end = pos1 + endStr.Length;
                        if(end < xmlText.Length)
                        {
                            xmlText = xmlText.Substring(0, end);
                            System.IO.File.WriteAllText(fileName, xmlText, Encoding.Default);
                            break;
                        }
                    }
                }

                ds.ReadXml(fileName);
              
            }
            return ds;
        }

2、调用

 if (System.IO.File.Exists(xml对应路径))
                {
                    DataSet ds = readXML(xml对应的路径文件);/                  
                    DataTable dt= ds.Tables[0];           //把dataset转换为datatable         
                }