最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C# 创建,读取,写入XML文件
时间:2022-06-25 07:51:11 编辑:袖梨 来源:一聚教程网
Xml文件如下:
代码如下 | 复制代码 |
|
对XML文件的操作
代码如下 | 复制代码 |
/// /// 创建XML文件 /// /// publicvoidCreateXmlFile(stringfilename) { XmlDocument xmldoc =newXmlDocument(); XmlNode node; node = xmldoc.CreateXmlDeclaration("1.0","utf-8",null); xmldoc.AppendChild(node); XmlNode root = xmldoc.CreateElement("Users"); xmldoc.AppendChild(root); CreateNode(xmldoc, root,"UserName","zhengyd"); CreateNode(xmldoc, root,"Email","[email protected],cn"); CreateNode(xmldoc, root,"Url","www.gucas.an,cn"); CreateNode(xmldoc, root,"Age","27"); try { xmldoc.Save(Server.MapPath(filename)); Response.Write("创建XML文件myxml.xml成功!"); } catch(Exception ex) { Response.Write(ex.Message); } } /// /// 写入XML文件 /// /// publicvoidWriteXmlFile(stringfile) { XmlDocument xmdoc =newXmlDocument(); try { xmdoc.Load(Server.MapPath(file)); XmlNode root = xmdoc.SelectSingleNode("Advertisements"); if(root !=null) { XmlNode node = xmdoc.CreateNode(XmlNodeType.Element,"Ad",null); CreateNode(xmdoc, node,"ImageUrl","google.gif"); CreateNode(xmdoc, node,"NavigateUrl","http://www.google.com"); CreateNode(xmdoc, node,"Impressions","30"); CreateNode(xmdoc, node,"Keyword","google"); root.AppendChild(node); } xmdoc.Save(Server.MapPath(file)); Response.Write("写入XML文件XMLFile.xml成功。 } catch(Exception ex) { Response.Write(ex.Message); } } /// /// 创建节点 /// /// /// /// /// publicvoidCreateNode(XmlDocument xmldoc, XmlNode parentnode,stringname,stringvalue) { XmlNode node = xmldoc.CreateNode(XmlNodeType.Element, name,null); node.InnerText = value; parentnode.AppendChild(node); } /// /// 读取XML文件 /// /// privatevoidReadFile(stringfile) { XmlDocument xmldoc =newXmlDocument(); try { xmldoc.Load(Server.MapPath(file)); XmlNode node = xmldoc.SelectSingleNode("Advertisements"); if(node !=null) { TreeNode root =newTreeNode(); root.Text = node.Name; tvXml.Nodes.Add(root); foreach(XmlNode xnodeinxmldoc.SelectNodes("Advertisements/Ad")) { TreeNode tnode =newTreeNode(); tnode.Text = Server.HtmlEncode("<"+ xnode.Name +">"); root.ChildNodes.Add(tnode); foreach(XmlNode xcnodeinxnode.ChildNodes) { TreeNode tcnode =newTreeNode(); tcnode.Text = Server.HtmlEncode("<"+ xcnode.Name +">"+ xcnode.InnerText +""+ xcnode.Name +">"); tnode.ChildNodes.Add(tcnode); } TreeNode ttnode =newTreeNode(); ttnode.Text = Server.HtmlEncode(""+ xnode.Name +""); root.ChildNodes.Add(ttnode); } TreeNode tpnode =newTreeNode(); tpnode.Text = Server.HtmlEncode(""+ node.Name +">"); tvXml.Nodes.Add(tpnode); } } catch(Exception ex) { Response.Write(ex.Message); } } |
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22