XML的应用还是很广泛的,有必要特地的学习一下
//读取XML文件,然后存入数据库
private void button1_Click(object sender,EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("../../Data.xml"); //上上个文件目录
//XmlNode xn = xmlDoc.SelectSingleNode("students"); //查找第一个节点
textBox1.Text = xmlDoc.InnerXml;
string str = "insert into xml values('" + xmlDoc.InnerXml + "')";
sqlHelper helper = new sqlHelper();
if (helper.insertData(str,CommandType.Text))
{
MessageBox.Show("存入成功!","提示");
}
else
{
MessageBox.Show("存入失败!","提示");
}
}
//读取所有的节点(包括元素节点和文本节点)
private void button2_Click(object sender,EventArgs e)
{
System.Xml.Linq.XElement xe = System.Xml.Linq.XElement.Load("../../Data.xml");
IEnumerable<System.Xml.Linq.XElement> elements = from ele in xe.Elements("student")
select ele;
showInfoByElements(elements);
}
/// <summary>
/// 读取所有的节点
/// </summary>
/// <param name="elements"></param>
private void showInfoByElements(IEnumerable<System.Xml.Linq.XElement> elements)
{
List<Model> modelList = new List<Model>();
foreach (var ele in elements)
{
Model model = new Model();
model.name = ele.Element("name").Value;
model.sex = ele.Element("sex").Value;
model.age = Convert.ToInt16(ele.Element("age").Value);
modelList.Add(model);
}
dataGridView1.DataSource=modelList;
}
//标题的改变
private void button3_Click(object sender,EventArgs e)
{
if (dataGridView1.ColumnCount<0)
{
dataGridView1.ColumnCount = 3;
dataGridView1.Rows.Add();
}
dataGridView1.Columns[0].HeaderCell.Value = "姓名";
dataGridView1.Columns[1].HeaderCell.Value = "性别";
dataGridView1.Columns[2].HeaderCell.Value = "年龄";
}