XML:可扩展的标记语言
XML:存储数据
XML是严格区分大小写
节点:一个又一个标签
根节点:整个xml文档中必须得有一个根节点,但是有且仅有一个根节点。
元素:xml文档中的所有内容都是元素
代码创建.xml文件
//通过代码创建xml文档
//1.引用命名空间 using System.Xml
//2.创建xml文档对象
XmlDocument doc = new XmlDocument();
//3.创建第一行描述信息
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
//4.创建根节点
XmlElement books = doc.CreateElement("Books");
//5.将根节点添加到文档中
doc.AppendChild(books);
//6.给根节点Books创建子节点
XmlElement book1 = doc.CreateElement("Book");
XmlElement book2 = doc.CreateElement("Book");
//7.将子节点Book添加到根节点
books.AppendChild(book1);
books.AppendChild(book2);
//8.给book1添加子节点
XmlElement name1 = doc.CreateElement("Name");
name1.InnerText = "西游记";
book1.AppendChild(name1);
XmlElement price1 = doc.CreateElement("Price");
price1.InnerText = "70";
book1.AppendChild(price1);
XmlElement name2 = doc.CreateElement("Name");
name2.InnerText = "水浒传";
book2.AppendChild(name2);
XmlElement price2 = doc.CreateElement("Price");
price2.InnerText = "90";
book2.AppendChild(price2);
doc.Save("Bean.xml");
Console.ReadKey();
创建带属性的.xml文件
//创建带属性的xml文档
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
XmlElement order = doc.CreateElement("Order");
doc.AppendChild(order);
XmlElement customerName = doc.CreateElement("CustomerName");
customerName.InnerText = "李宁";
order.AppendChild(customerName);
XmlElement customerNumber = doc.CreateElement("CustomerNumber");
customerNumber.InnerText = "1001";
order.AppendChild(customerNumber);
XmlElement items = doc.CreateElement("Items");
order.AppendChild(items);
XmlElement orderItem1 = doc.CreateElement("OrderItem");
XmlElement orderItem2 = doc.CreateElement("OrderItem");
//给节点添加属性
orderItem1.SetAttribute("Name", "铅笔");
orderItem1.SetAttribute("Count", "20");
items.AppendChild(orderItem1);
orderItem2.SetAttribute("Name", "橡皮");
orderItem2.SetAttribute("Count", "10");
items.AppendChild(orderItem2);
doc.Save("ConfigBase.xml"); //创建带属性的xml文档
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
XmlElement order = doc.CreateElement("Order");
doc.AppendChild(order);
XmlElement customerName = doc.CreateElement("CustomerName");
customerName.InnerText = "李宁";
order.AppendChild(customerName);
XmlElement customerNumber = doc.CreateElement("CustomerNumber");
customerNumber.InnerText = "1001";
order.AppendChild(customerNumber);
XmlElement items = doc.CreateElement("Items");
order.AppendChild(items);
XmlElement orderItem1 = doc.CreateElement("OrderItem");
XmlElement orderItem2 = doc.CreateElement("OrderItem");
//给节点添加属性
orderItem1.SetAttribute("Name", "铅笔");
orderItem1.SetAttribute("Count", "20");
items.AppendChild(orderItem1);
orderItem2.SetAttribute("Name", "橡皮");
orderItem2.SetAttribute("Count", "10");
items.AppendChild(orderItem2);
doc.Save("ConfigBase.xml");