先来个基础的Xml创建添加:
//创建对象 XmlDocument doc = new XmlDocument(); //创建行描述信息 XmlDeclaration xd = doc.CreateXmlDeclaration("1.0","utf-8",null); doc.AppendChild(xd); //添加根节点 XmlElement books= doc.CreateElement("Books"); doc.AppendChild(books); //给books添加子节点 XmlElement book1 = doc.CreateElement("book"); books.AppendChild(book1); //给book1添加文本,Name,Price XmlElement name1 = doc.CreateElement("Name"); name1.InnerText = "十万个为什么"; book1.AppendChild(name1); XmlElement price1 = doc.CreateElement("Price"); price1.InnerText = "25"; book1.AppendChild(price1);
生成的Xml文档:
<?xml version="1.0" encoding="utf-8"?> <Books> <book> <Name>十万个为什么</Name> <Price>25</Price> </book> </Books>
再来个有参数的,如下图:
<?xml version="1.0" encoding="utf-8"?> <Order> <CustomName>安妮</CustomName> <Items> <Item Name="Anni" Age="18" /> </Items> </Order>
上代码:
XmlDocument doc = new XmlDocument(); XmlDeclaration xd = doc.CreateXmlDeclaration("1.0","utf-8",null); doc.AppendChild(xd); XmlElement Order = doc.CreateElement("Order"); doc.AppendChild(Order); // XmlElement customName = doc.CreateElement("CustomName"); customName.InnerText = "安妮"; Order.AppendChild(customName); //创建带有属性的 XmlElement Items = doc.CreateElement("Items"); Order.AppendChild(Items); XmlElement item1 = doc.CreateElement("Item"); item1.SetAttribute("Name","Anni"); item1.SetAttribute("Age", "18"); Items.AppendChild(item1); doc.Save("Custom.xml"); Console.WriteLine("创建成功"); Console.ReadKey();