1. 创建步骤
XML:存储数据
创建XML文件注意:XML是严格区分大小写、成对出现的
元素:所有的内容都是元素)(Element)
节点:标签就是节点(Node)
XML文档有且只能有一个根节点
2. 代码实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace _02创建XML文件1
{
class Program
{
static void Main(string[] args)
{
//1、引用命名空间
//2、创建XML文件对象
XmlDocument doc = new XmlDocument();
//3/创建第一行表述信息,,并添加在doc文档中。
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);
//4、添加根节点
XmlElement books = doc.CreateElement("Books");
doc.AppendChild(books);
//5、给节点Books创建节点
XmlElement book1 = doc.CreateElement ("Book1");
books.AppendChild(book1);
//6、给Book1添加子节点
XmlElement name1 = doc.CreateElement("Name");
name1.InnerText="金瓶梅";
book1.AppendChild(name1);
XmlElement price1 = doc.CreateElement("Price");
price1.InnerText = "10";
book1.AppendChild(price1);
//5.2、给节点Books创建节点
XmlElement book2 = doc.CreateElement("Book2");
books.AppendChild(book2);
//6.2 给Book2添加子节点
XmlElement name2 = doc.CreateElement("Name2");
name2.InnerText = "水浒传";
book2.AppendChild(name2);
doc.Save("Books.xml");
//保存
Console.WriteLine("保存成功");
Console.ReadKey();
}
}
}
3. 实现结果