<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="读取Xml文件.aspx.cs" Inherits="Test.Web.读取Xml文件" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
后台
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 Test.Web { public partial class 读取Xml文件 : System.Web.UI.Page { protected void Page_Load(object sender,EventArgs e) { XMLopertator(); CreateXML(); SetElementValue(); } XmlDocument x = new XmlDocument();//实例化一个XML文档 /// <summary> /// 循环读取XML里的内容 /// </summary> public void XMLopertator() { XMLLoad(); XmlNodeList xnl = x.ChildNodes; foreach (XmlNode xn in xnl) { XmlNodeList xnl1 = xn.ChildNodes; foreach (XmlNode xn1 in xnl1) { XmlNodeList xnl2 = xn1.ChildNodes; foreach (XmlNode xn2 in xnl2) { Response.Write(xn2.Attributes["text"].Value + "<br/>");//属性是text的值 } } } } /// <summary> /// 加载XML文档 /// </summary> public void XMLLoad() { x.Load(Server.MapPath("/FileBase/zgw.xml"));//加载xml文档 } /// <summary> /// 创建XML文档 /// </summary> private void CreateXML() { //<user > //<name id="OK"> //<z></z> //</name> //</user> XmlDocument xx = new XmlDocument();//创建xml文档 XmlElement root = xx.CreateElement("user");//创建根节点 xx.AppendChild(root);//把根节点放到xml中 XmlElement name = xx.CreateElement("name");//创建元素 XmlAttribute nameid = xx.CreateAttribute("id");//创建元素属性 nameid.Value = "OK";//元素属性的值 name.Attributes.Append(nameid);//把元素放到节点中 XmlElement z = xx.CreateElement("z");//创建元素 z.InnerText = "one";//元素的值 name.AppendChild(z);// root.AppendChild(name);//把节点放到根节点中 xx.Save(Server.MapPath("/FileBase/ceshi1.xml"));//保存 } /// <summary> /// 编辑Xml文档 /// </summary> private void SetElementValue() { XmlDocument xxx = new XmlDocument();//实例化 xxx.Load(Server.MapPath("/FileBase/ceshi.xml"));//加载文档 XmlNode xn = xxx.SelectSingleNode("//z[@id='4565']");//找到文档中元素是z id是4565的的第一个 XmlAttribute ztitle = xxx.CreateAttribute("title");//创建元素属性 ztitle.Value = "xml属性值";//给属性赋值 xn.Attributes.Append(ztitle);//添加到元素中 xn.InnerText = "OK";//设置值 xxx.Save(Server.MapPath("/FileBase/ceshi.xml"));//保存 } } }