添加一个winform窗体,添加一个按钮事件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
//定义公共对象:
XmlDocument xmldoc ;
XmlElement xmlelement;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
xmldoc = new XmlDocument();
//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
XmlDeclaration xmldeclaration;
xmldeclaration = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
xmldoc.AppendChild(xmldeclaration);
//加入一个根元素
xmlelement = xmldoc.CreateElement("", "Books", "");
xmldoc.AppendChild(xmlelement);
//加入另外一个元素
for (int i = 1; i < 5; i++)
{
XmlNode root = xmldoc.SelectSingleNode("Books");//查找<Books>
XmlElement dot = xmldoc.CreateElement("Node");//创建一个<Node>节点
dot.SetAttribute("developer", "开发人");//设置该节点genre属性
dot.SetAttribute("ISBN", "23456");//设置该节点ISBN属性
XmlElement sub1 = xmldoc.CreateElement("title");
sub1.InnerText = "c#winform开发";//设置文本节点
dot.AppendChild(sub1);//添加到<Node>节点中
XmlElement sub2 = xmldoc.CreateElement("author");
sub2.InnerText = "li";
dot.AppendChild(sub2);
XmlElement sub3 = xmldoc.CreateElement("price");
sub3.InnerText = "100";
dot.AppendChild(sub3);
root.AppendChild(dot);//添加到<Employees>节点中
}
//保存创建好的XML文档
xmldoc.Save(Environment.CurrentDirectory + "\\" + "data.xml");
}
}
}