C#创建XML文件

 XmlDocument xmldoc = new XmlDocument();            

            //加入XML的声明段落

            xmldoc.AppendChild(xmldoc.CreateXmlDeclaration("1.0","UTF-8",null));

            //加入根元素

            XmlElement xmlelem = xmldoc.CreateElement("", "Books", "");

            xmldoc.AppendChild(xmlelem);

            //FileName

            XmlElement xmlelemFileName = xmldoc.CreateElement("FileName");

            XmlText xmltextFileName = xmldoc.CreateTextNode("书籍文件列表");

            xmlelemFileName.AppendChild(xmltextFileName);

            xmldoc.ChildNodes.Item(1).AppendChild(xmlelemFileName);



            //UserInfo

            XmlElement xmlelemUserInfo = xmldoc.CreateElement("UserInfo");

            xmldoc.ChildNodes.Item(1).AppendChild(xmlelemUserInfo);

            //UserName

            XmlElement xmlelemUserName = xmldoc.CreateElement("UserName");

            XmlText xmltextUserName = xmldoc.CreateTextNode("cainiaoji");//用户名

            xmlelemUserName.AppendChild(xmltextUserName);

            xmldoc.ChildNodes.Item(1).ChildNodes[1].AppendChild(xmlelemUserName);



            //ChineseBook

            XmlElement xmlelemChineseBook = xmldoc.CreateElement("ChineseBook");

            xmldoc.ChildNodes.Item(1).AppendChild(xmlelemChineseBook);

            //Book1

            XmlElement xmlelemBook1 = xmldoc.CreateElement("Book1");

            xmlelemBook1.SetAttribute("BookCode", "001");

            xmldoc.ChildNodes.Item(1).ChildNodes[2].AppendChild(xmlelemBook1);

            //BookName

            XmlElement xmlelemBookName = xmldoc.CreateElement("BookName");

            XmlText xmltextBookName = xmldoc.CreateTextNode("小学语文");//书名

            xmlelemBookName.AppendChild(xmltextBookName);

            xmldoc.ChildNodes.Item(1).ChildNodes[2].ChildNodes[0].AppendChild(xmlelemBookName);

            //publishing house

            XmlElement xmlelemph = xmldoc.CreateElement("PublishingHouse");

            XmlText xmltextph = xmldoc.CreateTextNode("电子工业出版社");//出版社

            xmlelemph.AppendChild(xmltextph);

            xmldoc.ChildNodes.Item(1).ChildNodes[2].ChildNodes[0].AppendChild(xmlelemph);

            try

            {

                xmldoc.Save("c:\\cc.xml");

            }

            catch (Exception e)

            {

                //显示错误信息

                Console.WriteLine(e.Message);

            }

            Console.ReadLine();

你可能感兴趣的:(xml)