读取和操作xml文件System.Xml (c#)

来源:互联网 发布:单片机控制电磁铁 编辑:程序博客网 时间:2024/05/20 07:19

private void button1_Click(object sender, System.EventArgs e)
  {
   string connStr = "server=.;uid = sa;pwd=;database=northwind";
   SqlConnection con = new SqlConnection(connStr);
   DataSet ds = new DataSet("XMLProducts");
   SqlDataAdapter sda = new SqlDataAdapter("select * from products",con);
   MemoryStream memStream = new MemoryStream();
   StreamReader strmRead = new StreamReader(memStream);
   StreamWriter strmWrite = new StreamWriter(memStream);
   sda.Fill(ds,"products");
   this.dataGrid1.DataSource = ds;
   this.dataGrid1.DataMember = "products";
   ds.WriteXml(strmWrite,XmlWriteMode.IgnoreSchema);
   memStream.Seek(0,SeekOrigin.Begin);
   XmlDocument doc = new XmlDocument();
   doc.Load(strmRead);
   XmlNodeList nodeLst = doc.GetElementsByTagName("ProductName");
   foreach(XmlNode node in nodeLst)
   {
    this.listBox1.Items.Add(node.InnerText);
   }
   string file = @"D:/product.xml";
   ds.WriteXml(file);
  }

  private void button2_Click(object sender, System.EventArgs e)
  {
   XmlDataDocument doc;
   string connStr = "server=.;uid = sa;pwd=;database=northwind";
   SqlConnection con = new SqlConnection(connStr);
   DataSet ds = new DataSet("XMLProducts");
   SqlDataAdapter sda = new SqlDataAdapter("select * from products",con);
   sda.Fill(ds,"products");
   this.dataGrid1.DataSource = ds;
   this.dataGrid1.DataMember = "products";
   doc = new XmlDataDocument(ds);
   ds.WriteXml(@"D:/Button2.xml",XmlWriteMode.WriteSchema);
  }

  private void button3_Click(object sender, System.EventArgs e)
  {
   DataSet ds = new DataSet("XMLProducts");
   ds.ReadXml(@"D:/Button2.xml");
   this.dataGrid1.DataSource = ds;
   this.dataGrid1.DataMember = "products";
   XmlDataDocument doc = new XmlDataDocument(ds);
   XmlNodeList nodeLst = doc.SelectNodes("//ProductName");
   foreach(XmlNode nd in nodeLst)
   {
    this.listBox1.Items.Add(nd.InnerXml);
   }
  }