C#学习笔记之创建Xml文档

来源:互联网 发布:西门子plc伺服编程 编辑:程序博客网 时间:2024/04/30 01:09
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 创建Xml{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            // 声明一个Xml文档对象            XmlDocument doc = new XmlDocument();            // 创建Xml描述信息            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);            doc.AppendChild(dec);            // 创建根节点            XmlElement root = doc.CreateElement("Root");            doc.AppendChild(root);            // 给根节点创建子节点            XmlElement books = doc.CreateElement("Books");            root.AppendChild(books);            // 给子节点添加元素            XmlElement name1 = doc.CreateElement("Name");            name1.InnerText = "西游记";            books.AppendChild(name1);            XmlElement price1 = doc.CreateElement("Price");            price1.InnerText = "33";            books.AppendChild(price1);            XmlElement name2 = doc.CreateElement("Name");            name2.InnerText = "水浒传";            books.AppendChild(name2);            XmlElement price2 = doc.CreateElement("Price");            price2.InnerText = "22";    <span style="white-space:pre"></span>// 添加文本信息            books.AppendChild(price2);            XmlElement name3 = doc.CreateElement("标签");            name3.InnerXml = "<p>我是一个标签</p>";   <span style="white-space:pre"></span>// 添加标签            books.AppendChild(name3);            // 保存Xml文档时,必须要有根元素            doc.Save("XmlDoc.xml");            MessageBox.Show("创建成功");        }    }}


0 0