C#将XML导入到ACCESS数据库

转自:http://tech.it168.com/a2009/0313/268/000000268469.shtml

  【IT168 技术文档】

  假设有如下的XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<users>
  
<user code="lm">
    
<name>黎明</name>
    
<sex>male</sex>
    
<age>28</age>
  
</user>
  
<user code="sq">
    
<name>舒淇</name>
    
<sex>female</sex>
    
<age>27</age>
  
</user>
</users>

  代码如下:

//请将ACCESS数据库的路径替换为实际的路径
using (OleDbConnection cn =new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=d:\demo.mdb"))
{
    cn.Open();
    
using (OleDbCommand cmd =new OleDbCommand())
    {
        cmd.Connection
= cn;
        cmd.CommandType
= CommandType.Text;
        
        XmlDocument xml
=new XmlDocument();
        
//请将XML的路径替换为实际的路径
        xml.Load(@"d:\demo.xml");

        
//取得所有的user
        XmlNodeList xn = xml.GetElementsByTagName("user");

        
//遍历所有的user
        foreach (XmlElement xe in xn)
        {
            cmd.CommandText
=string.Format("INSERT INTO userinfo([UserCode],[UserName],[UserSex],[UserAge]) VALUES ('{0}', '{1}', '{2}', {3})",
            xe.GetAttribute(
"code"),    //取得code
            xe.ChildNodes[0].InnerText, //取得Name
            xe.ChildNodes[1].InnerText, //取得Sex
            xe.ChildNodes[2].InnerText  //取得Age
            );

            
//插入数据
            cmd.ExecuteNonQuery();
        }
    }
}

posted on 2011-12-28 14:00  beiyd  阅读(146)  评论(0编辑  收藏  举报

导航