C# XML基本操作1-创建XML文件在当前目录下

添加一个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");


        }
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT技术与企业应用结合的爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值