将xml文档保存到数据库,可以通过linq来解析。首先在项目中用linq to sql将需要操作的表建立起对象关系映射。然后读取xml文档,解析并保存。下面的代码演示了读取磁盘某路径下存放的所有xml文件,解析保存到数据库后删除文件。xml文档格式可能如下:<?xml version="1.0" encoding="gb2312" ?> - <Body> <Head fsfid="000242102240100" jsfid="" sjblx="0001" jcsbid="" jls="442" wjscsj="20100813173419" sjcssj="20100813160000" /> - <Data> - <Item pollutant_code="002"> <Avg>00.001</Avg> <Max>00.002</Max> <Min>00.001</Min> </Item> - <Item pollutant_code="005"> <Avg>00.002</Avg> <Max>00.002</Max> <Min>00.001</Min> </Item> - <Item pollutant_code="001"> <Avg>00.038</Avg> <Max>00.044</Max> <Min>00.034</Min> </Item> </Data> </Body>
其中Head元素的fsfid属性以及sjcssj属性是需要读取后解析的。
完全的解析代码如下: public static void xmltodb() { testDataContext t = new testDataContext(); String path = "C://xml";//存放xml文件的路径 String[] files = Directory.GetFiles(path);//得到所有文件路径 List<AirHour> ahlist = new List<AirHour>(); foreach (String s in files) { XElement root = XElement.Load(s);//加载xml文件 var header = from head in root.Elements("Head") select new{codes= head.Attribute("fsfid").Value,times=head.Attribute("sjcssj").Value}; string codes = header.First().codes; int stcode =Int32.Parse( codes.Substring(4,6));//城市id string stname = t.StationDistricts.Where(d=>d.stcode==stcode).Select(d=>d.stname).First();//城市名称 int stationcode =Int32.Parse( codes.Substring(10, 3));//监测站id string pname = t.StationDistricts.Where(d => d.stcode == stcode & d.pcode == stationcode).Select(d => d.pname).First();//监测站名称 string times = header.First().times; int year =Int32.Parse( times.Substring(0,4));//年 int month = Int32.Parse(times.Substring(4,2));//月 int day = Int32.Parse(times.Substring(6,2));//日 int hour = Int32.Parse(times.Substring(8,2));//小时 int minute = Int32.Parse(times.Substring(10,2));//分钟 int second = Int32.Parse(times.Substring(12,2));//秒 DateTime time = new DateTime(year,month,day,hour,minute,second);//时间 if (root.Elements("Data").Elements("Item").Elements("Avg").Any()) { var itemList = from ele in root.Elements("Data").Elements("Item") select new { pcode = ele.Attribute("pollutant_code").Value, pvalue = ele.Element("Avg").Value }; foreach (var item in itemList) { AirHour ah = new AirHour(); ah.stime = time; ah.stname = stname; ah.stcode = stcode; ah.pname = pname; ah.pcode = stationcode; string item_code = item.pcode;//监测项代码 if(t.AllItems.Where(i => i.item_code == item_code).Any()) ah.itemname = t.AllItems.Where(i => i.item_code == item_code).Select(i => i.item_name).First();//监测项目名称 ah.itemvalue = decimal.Parse(itemList.First().pvalue);//监测项目值 ahlist.Add(ah); } } else{...} t.AirHours.InsertAllOnSubmit(ahlist); t.SubmitChanges(); }