XML file如下 :
<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
<book genre="autobiography">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book genre="novel">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy">
<title>The Gorgias</title>
<author>
<first-name>Tony</first-name>
<last-name>wei</last-name>
</author>
<price>9.99</price>
</book>
</bookstore>
C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Data.SqlClient;
namespace Frm_conn_XML
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strFileName = "Books.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFileName))
{
XmlTextReader reader = new XmlTextReader(strFileName);
string title = "";
string first_name = "";
string last_name = "";
string price = "";
while (reader.Read())
{
if (reader.Name == "title")
{
reader.Read();
title = reader.Value;
MessageBox.Show(title);
reader.Read();
reader.Read();
}
if (reader.Name == "first-name")
{
reader.Read();
first_name = reader.Value;
MessageBox.Show(first_name);
reader.Read();
reader.Read();
}
if (reader.Name == "last-name")
{
reader.Read();
last_name = reader.Value;
MessageBox.Show(last_name);
reader.Read();
reader.Read();
}
if (reader.Name == "price")
{
reader.Read();
price = reader.Value;
MessageBox.Show(price);
reader.Read();
reader.Read();
try
{
string connStr = @"Data Source=*****\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Pooling=False";
string sqlCom = "Insert into test1(title,fN,lN,price) values('" + title + "','" + first_name + "','" + last_name + "','"+price+"')";
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = sqlCom;
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
MessageBox.Show("新增資料成功!");
}
catch
{
MessageBox.Show("false");
}
}}}}}}