标签:
//通过代码创建XML文档 //引用命名空间using System.Xml; //创建xml对像 XmlDocument doc = new XmlDocument(); //添加描述到文档 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(dec); //创建根节点 XmlElement Books = doc.CreateElement("Books"); //把根节点添加到文档 doc.AppendChild(Books); //给根节点创建子节点 XmlElement book1 = doc.CreateElement("book"); //把book添加到根结点 Books.AppendChild(book1); //给book1添加子节点 XmlElement name1 = doc.CreateElement("Name"); name1.InnerText = "第一本书"; book1.AppendChild(name1); XmlElement pri1 = doc.CreateElement("Pri"); pri1.InnerText = "110"; book1.AppendChild(pri1); XmlElement con1 = doc.CreateElement("Con"); con1.InnerText = "很好看"; book1.AppendChild(con1); //给根节点创建子节点2 XmlElement book2= doc.CreateElement("book"); //把book添加到根结点 Books.AppendChild(book2); //给book1添加子节点 XmlElement name2= doc.CreateElement("Name"); name2.InnerText = "第二本书"; book2.AppendChild(name1); XmlElement pri2 = doc.CreateElement("Pri"); pri2.InnerText = "220"; book2.AppendChild(pri1); XmlElement con2 = doc.CreateElement("Con"); con2.InnerText = "一点也不很好看"; book2.AppendChild(con1); doc.Save("xml.xml");
输出结果
<?xml version="1.0" encoding="utf-8"?> <Books> <book> </book> <book> <Name>第一本书</Name> <Pri>110</Pri> <Con>很好看</Con> </book> </Books>
//通过代码创建XML文档 //引用命名空间using System.Xml; //创建xml对像 XmlDocument doc = new XmlDocument(); //添加描述到文档 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(dec); //创建根节点 XmlElement Books = doc.CreateElement("Books"); //把根节点添加到文档 doc.AppendChild(Books); //给根节点创建子节点 XmlElement book1 = doc.CreateElement("book"); //把book添加到根结点 Books.AppendChild(book1); //给book1添加子节点 XmlElement name1 = doc.CreateElement("Name"); name1.InnerText = "第一本书"; book1.AppendChild(name1); XmlElement pri1 = doc.CreateElement("Pri"); pri1.InnerText = "110"; book1.AppendChild(pri1); XmlElement con1 = doc.CreateElement("Con"); con1.InnerText = "很好看"; book1.AppendChild(con1); //创建新节点 XmlElement xlist = doc.CreateElement("list"); book1.AppendChild(xlist); XmlElement xitem1 = doc.CreateElement("item"); //创建添加属性 xitem1.SetAttribute("name", "这是什么啊"); xitem1.SetAttribute("conut", "100"); xlist.AppendChild(xitem1); //创建新节点 XmlElement xitem2 = doc.CreateElement("item"); //创建添加属性 xitem2.SetAttribute("name", "不知道"); xitem2.SetAttribute("conut", "1001"); xlist.AppendChild(xitem2); doc.Save("xml.xml");
输出结果
<?xml version="1.0" encoding="utf-8"?> <Books> <book> <Name>第一本书</Name> <Pri>110</Pri> <Con>很好看</Con> <list> <item name="这是什么啊" conut="100" /> <item name="不知道" conut="1001" /> </list> </book> </Books>
标签:
原文地址:http://www.cnblogs.com/zywf/p/4564739.html