C# 创建,读取,写入 XML文件

Xml文件如下:

 001.jpg 001.aspx 10 gucas01 002.jpg 002.aspx 20 gucas02 003.jpg 003.aspx 30 gucas03 004.jpg 004.aspx 40 gucas04 005.jpg 005.aspx 50 gucas05 google.gif http://www.google.com 30 google

 

对XML文件的操作

 

///

/// 创建XML文件 /// /// public void CreateXmlFile(string filename) { XmlDocument xmldoc = new XmlDocument(); 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文件 /// /// public void WriteXmlFile(string file) { XmlDocument xmdoc = new XmlDocument(); 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); } } /// /// 创建节点 /// /// /// /// /// public void CreateNode(XmlDocument xmldoc, XmlNode parentnode, string name, string value) { XmlNode node = xmldoc.CreateNode(XmlNodeType.Element, name, null); node.InnerText = value; parentnode.AppendChild(node); } /// /// 读取XML文件 /// /// private void ReadFile(string file) { XmlDocument xmldoc = new XmlDocument(); try { xmldoc.Load(Server.MapPath(file)); XmlNode node = xmldoc.SelectSingleNode("Advertisements"); if (node != null) { TreeNode root = new TreeNode(); root.Text = node.Name; tvXml.Nodes.Add(root); foreach (XmlNode xnode in xmldoc.SelectNodes("Advertisements/Ad")) { TreeNode tnode = new TreeNode(); tnode.Text = Server.HtmlEncode("<" + xnode.Name + ">"); root.ChildNodes.Add(tnode); foreach (XmlNode xcnode in xnode.ChildNodes) { TreeNode tcnode = new TreeNode(); tcnode.Text = Server.HtmlEncode("<" + xcnode.Name + ">" + xcnode.InnerText + ""); tnode.ChildNodes.Add(tcnode); } TreeNode ttnode = new TreeNode(); ttnode.Text = Server.HtmlEncode(""); tvXml.Nodes.Add(tpnode); } } catch (Exception ex) { Response.Write(ex.Message); } }

你可能感兴趣的:(C#,xml,c#,exception,string,null,file)