C#创建XML文件教程经典案例 自定义保存目录路径
用法推荐:
下面我们来看下具体代码吧:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; namespace CreateXML { public partial class CreateXMLTest : System.Web.UI.Page { /// <summary> /// C#经典创建XML教程案例 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { 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("Json在线工具http://www.jsons.cn"); 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("Json解析");//网站名称 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("C#高级编程");//书名 xmlelemBookName.AppendChild(xmltextBookName); xmldoc.ChildNodes.Item(1).ChildNodes[2].ChildNodes[0].AppendChild(xmlelemBookName); //publishing house XmlElement xmlelemph = xmldoc.CreateElement("PublishingHouse"); XmlText xmltextph = xmldoc.CreateTextNode("来源:Jsons.cn");//出版社 xmlelemph.AppendChild(xmltextph); xmldoc.ChildNodes.Item(1).ChildNodes[2].ChildNodes[0].AppendChild(xmlelemph); try { xmldoc.Save("d:\\createdemo.xml");//自定义文件保存目录 Response.Write("创建成功"); } catch { //显示错误信息 Response.Write("异常"); } } } }
原文链接:C#创建XML文件教程经典案例