不带属性的xml文件格式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace xml
{
class Program
{
static void Main(string[] args)
{
//在内存中创建xml对象;
XmlDocument xdc = new XmlDocument();
//创建第一行xml信息;
XmlDeclaration dec = xdc.CreateXmlDeclaration("1.0", "utf-8", null);
//将第一行信息放到xdc中;
xdc.AppendChild(dec);
//创建根节点
XmlElement xn = xdc.CreateElement("Books");
xdc.AppendChild(xn);
//创建子节点
XmlElement book= xdc.CreateElement("Book");
xn.AppendChild(book);
//给book创建name子节点
XmlElement name = xdc.CreateElement("name");
name.InnerText = "c#";
book.AppendChild(name);
//给book创建price子节点
XmlElement price = xdc.CreateElement("price");
price.InnerText = "23";
book.AppendChild(price);
//给book创建desc子节点
XmlElement desc = xdc.CreateElement("desc");
desc.InnerText = "这本书不错!";
book.AppendChild(desc);
xdc.Save("file.xml");
}
}
}
带属性的xml格式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace 带属性的xml文件
{
class Program
{
static void Main(string[] args)
{
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 cust= doc.CreateElement("CustomerName");
cust.InnerText ="张三";
order.AppendChild(cust);
XmlElement ordern = doc.CreateElement("OrderNumber");
ordern.InnerText = "zs000000555";
order.AppendChild(ordern);
XmlElement items = doc.CreateElement("items");
order.AppendChild(items);
XmlElement orderitem1 = doc.CreateElement("orderitem");
orderitem1.SetAttribute("Name","鱼香肉丝");
orderitem1.SetAttribute("price","20");
items.AppendChild(orderitem1);
XmlElement orderitem2 = doc.CreateElement("orderitem");
orderitem2.SetAttribute("Name", "宫保鸡丁");
orderitem2.SetAttribute("price", "40");
items.AppendChild(orderitem2);
doc.Save("attribu.xml");
}
}
}