XML和ADO.NET 的使用

来源:互联网 发布:linux golang 1.8 编辑:程序博客网 时间:2024/05/29 03:32

XML和ADO.NET 的使用

之前我们做的最多的就是在项目中建个配置文件来读取链接数据库的信息,现在我们来学习一下如何用xml来与数据库操作 :
首先你要在项目中的bin目录下建一个xml文件,实例

//请把*换成<
*Log KeepDays=”7” Threads=”3” BatchInsert=”500” StartTime=”17:19:00”>
*Site>
LogVersion>IIS7 /LogVersion>
SqlConnString>Integrated Security=False;server=172.168.30.167;database=iislog;User ID=sa;Password=lxf@1234656;Connect Timeout=30 /SqlConnString>
Server>172.168.30.167 /Server>
*/Site>
*/Log>
命名为LogData.xml

然后就是读取了。这里我要获取 Log里属性的StartTime值,写法如下:
string workPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
workPath = System.IO.Path.GetDirectoryName(workPath);
string path = workPath + @”\LogData.xml”;
XmlDocument xml = new XmlDocument();
xml.Load(path);

        XmlNode xnRoot = xml.SelectSingleNode("Log");                resulut = xnRoot.Attributes["StartTime"].Value;    

像 KeepDays这样的可能要取整数,可以加Convert.ToInt32(xnRoot.Attributes[“StartTime”].Value)来转换
获取SqlConnString的值写法:
要先获取节点
string workPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
workPath = System.IO.Path.GetDirectoryName(workPath);
XmlDocument xml = new XmlDocument();
xml.Load(path);
XmlNode xnRoot = xml.SelectSingleNode(“Log”);
XmlNodeList xnList = xnRoot.SelectNodes(“Site”);

//偷懒写法
string sqlcon=xnList.SelectSingleNode(“SqlConnString”).InnerText.Trim();

//可能有很多或者说集合 大同小异
foreach (XmlNode xn in xnList)
{
Log log = new Log();//自己创建的model类 里面的属性和xml文档里的节点相对应
if (xn.SelectSingleNode(“LogPath”) != null)
{
log.LogPath = xn.SelectSingleNode(“LogPath”).InnerText.Trim();
if (!log.LogPath.EndsWith(“\”)) log.LogPath += “\”;
}
log.LogVersion = xn.SelectSingleNode(“LogVersion”).InnerText.Trim();
log.SqlConnString = xn.SelectSingleNode(“SqlConnString”).InnerText.Trim();
if (xn.SelectSingleNode(“Server”) != null)
{
log.Server = xn.SelectSingleNode(“Server”).InnerText.Trim();
}
if (xn.SelectSingleNode(“TableName”) != null)
{
log.TableName = xn.SelectSingleNode(“TableName”).InnerText.Trim();
}
logList.Add(log);
}
}

0 0
原创粉丝点击