Declare, create, create the root node, add the sub-node of Books, and finally save the document (if the file already exists, update it; if not, create the file), friends who don’t know how can learn more
The code is as follows:
protected void Button1_Click(object sender, EventArgs e)//创建xml { //声明 XmlDocument x = new XmlDocument(); //创建 XmlDeclaration xd = x.CreateXmlDeclaration("1.0", "GB2312", null); x.AppendChild(xd); //创建根节点 XmlElement element = x.CreateElement("Books"); x.AppendChild(element); //添加Books的子节点 XmlNode book = x.CreateElement("Book"); //给Book添加元素 XmlElement bookname = x.CreateElement("书名"); bookname.InnerText = "三国"; //逐级添加到节点上 book.AppendChild(bookname); element.AppendChild(book); x.AppendChild(element); //保存文档(如果已经存在该文件,则更新之;如果没有,则创建该文件) x.Save(@"F:/Books.xml"); }
The above is the detailed content of Sample code sharing for creating root node and child nodes in xml. For more information, please follow other related articles on the PHP Chinese website!