private void btnWrite_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim().Length == 0)
{
MessageBox.Show("沒有輸入學(xué)生姓名", "友情提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtName.Focus();
return;
}
dlgSave.Filter= "*.xml|*.xml";
dlgSave.InitialDirectory=Application.StartupPath + @"\xml";
dlgSave.RestoreDirectory = true;
dlgSave.OverwritePrompt = false;
if (dlgSave.ShowDialog() == DialogResult.OK)
{
XmlDocument xmlDoc = new XmlDocument();
FileInfo fi = new FileInfo(dlgSave.FileName);
XmlNode root = null;
if (!fi.Exists)
{
flag = true;
XmlNode xmlnode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmlDoc.AppendChild(xmlnode);
root = xmlDoc.CreateNode(XmlNodeType.Element, "成績單", null);
xmlDoc.AppendChild(root);
}
else
{
flag = false;
xmlDoc.Load(dlgSave.FileName);
root = xmlDoc.SelectSingleNode("成績單");//查找<成績單>
}
XmlComment xc = xmlDoc.CreateComment(cbComment.Text);//創(chuàng)建一個注釋
root.AppendChild(xc);
XmlElement xe1 = xmlDoc.CreateElement("學(xué)生");//創(chuàng)建一個<學(xué)生>節(jié)點
xe1.SetAttribute("性別", (rbMen.Checked) ? "男" : "女");//設(shè)置該節(jié)點性別屬性
string sTemp = nudID.Value.ToString();
xe1.SetAttribute("學(xué)號", lab0512.Text + ((sTemp.Length == 1) ? "0" : "") + sTemp);//設(shè)置該節(jié)點學(xué)號屬性
XmlElement xesub1 = xmlDoc.CreateElement("姓名");
xesub1.InnerText = txtName.Text;//設(shè)置文本節(jié)點
xe1.AppendChild(xesub1);//添加到<學(xué)生>節(jié)點中
XmlElement xesub2 = xmlDoc.CreateElement("分數(shù)");
XmlElement xesub20 = xmlDoc.CreateElement("語文");
xesub20.InnerText = nudyw.Value.ToString();
xesub2.AppendChild(xesub20);
XmlElement xesub21 = xmlDoc.CreateElement("數(shù)學(xué)");
xesub21.InnerText = nudsx.Value.ToString();
xesub2.AppendChild(xesub21);
XmlElement xesub22 = xmlDoc.CreateElement("外語");
xesub22.InnerText = nudwy.Value.ToString();
xesub2.AppendChild(xesub22);
xe1.AppendChild(xesub2);
XmlElement xesub3 = xmlDoc.CreateElement("城市");
if (cmbCity.SelectedIndex != -1)
xesub3.InnerText = cmbCity.SelectedItem.ToString();
else
xesub3.InnerText = "本地";
xe1.AppendChild(xesub3);
root.AppendChild(xe1);//添加到<bookstore>節(jié)點中
xmlDoc.Save(dlgSave.FileName);
if (flag)
MessageBox.Show("成功生成XML文件!","系統(tǒng)提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
else
MessageBox.Show("信息已加入XML文件!" , "系統(tǒng)提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
cbComment.SelectedIndex = 0;
nudID.Value = 1;
txtName.Text = "";
nudyw.Value = nudsx.Value = nudwy.Value = 60;
rbMen.Checked = true;
rbWomen.Checked = false;
cmbCity.SelectedIndex = 0;
}
}
運行效果圖如下:
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

