小弟是菜鸟中的菜鸟,现在学习中遇到了一些问题想不明白,问的不好做的不对的,欢迎大牛来拍砖
 static void Main(string[] args)
        {
            string sqlcon = @"Data Source=PC-201206030428\Dool;Initial Catalog=MyName;User Id=sa;Password=*****";
            using (SqlConnection con = new SqlConnection(sqlcon))
            {
                string sql = "select * from ADOPerson";
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    if (con.State ==  System.Data.ConnectionState.Closed )
                    {
                        con.Open();
                    }
                    SqlDataReader reader = cmd.ExecuteReader();
                    using (reader)
                    {
                        if (reader.HasRows )
                        {
                            XElement xdoc = new XElement("Root");
                            while (reader.Read())
                            {
                                int id = reader.GetInt32(1);
                                string name = reader.GetString(2);
                                char sex =Convert .ToChar ( reader[3]);
                                int age = reader.GetInt32(4);
                               
                                XElement xperson = new XElement("Person");
                                xdoc.Add(xperson);
                                XElement xname = new XElement("Name");
                                xperson.Add(xname );
                                XElement xsex = new XElement("Sex");
                                xperson.Add(xsex);
                                XElement xage = new XElement("Age");    
                                xperson.Add(xage );
                                xperson.SetAttributeValue("id", id);
                                xname.Value  = name;
                                xage.Value  = age.ToString ();
                                xsex.Value = sex.ToString ();
                              
                            }                             //上面是我从数据库里导出来的1000条数据,要把他们放到xml文件里
                            xdoc.Save("E:\\derive.xml");  //我的问题是这里的save方法是怎么做到一次性把一千条数据写到xml文件里的呢?上面的while循环了1000次那些值都存到哪里去了呢?save方法里面是怎样的运行原理?
                        }
                    }
                }
            }
        }

解决方案 »

  1.   

    代码中没有1000次这个逻辑。while (reader.Read())
    {
        ...
    }这个循环表示,读取一条数据处理一条数据,直到读完。
      

  2.   

    while (reader.Read())循环读取每一条数据,然后添加到 xdoc中,直到循环完毕,然后保存doc
      

  3.   


      while (reader.Read())
      {
         ...
         xdoc.Add(xperson);
         ...
      }上面代码的作用是遍历你通过sql语句获得的结果,把每一条记录都添加到xml对象中
    最后提交保存。记录的数量由你查询的结果决定。
      

  4.   

    数据多的话,最好使用XmlTextWriter,以提高性能http://msdn.microsoft.com/zh-cn/library/wkee9k2s%28VS.80%29.aspx