asp.net 讀寫XML文件

本文介绍如何使用C#进行XML文件的基本操作,包括读取、更新和创建XML文件的方法。通过实例演示了如何选取节点、获取节点内容及遍历节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

讀取XML內容

            XmlDocument xml=new XmlDocument();
            xml.Load(Server.MapPath("text.xml"));
            XmlNode node = xml.SelectSingleNode("root");//根節點
            XmlNode nd = node.SelectSingleNode("city");//根據根節點獲取子節點
            TextBox1.Text = nd.InnerText;//讀出節點“city”的內容
            XmlNodeList nodelist = xml.SelectNodes("root");
            //遍歷所有節點的內容
            foreach (XmlNode node1 in nodelist)
            {
                ListBox1.Items.Add(node1.InnerText);
            }


更新XML文件

    XmlDocument xml = new XmlDocument();
            xml.Load(Server.MapPath("text.xml"));
            XmlNode node = xml.SelectSingleNode("root");//根節點
            XmlNode nd = node.SelectSingleNode("city");//根據根節點獲取子節點
            TextBox1.Text = nd.InnerText;//讀出節點“city”的內容
            nd.InnerText = "胡樓";
            xml.Save(Server.MapPath("text.xml"));


創建XML文件

        XmlDocument xml = new XmlDocument();
            XmlNode node = xml.CreateXmlDeclaration("1.0","big5","");
            xml.AppendChild(node);
            //新建根節點
            XmlNode root = xml.CreateElement("rui");
            xml.AppendChild(root);
            XmlNode a=xml.CreateNode(XmlNodeType.Element,"city","");
            a.InnerText = "深圳";
            root.AppendChild(a);
            XmlNode b=xml.CreateNode(XmlNodeType.Element,"address","");
            b.InnerText = "MSI";
            root.AppendChild(b);
            XmlNode c = xml.CreateNode(XmlNodeType.Element,"time","");
            c.InnerText = "8:30";
            root.AppendChild(c);

            //新建一個父節點
            XmlNode item = xml.CreateNode(XmlNodeType.Element,"item","");
            root.AppendChild(item);//追加到根節點
            XmlNode a1 = xml.CreateNode(XmlNodeType.Element,"city","");
            a1.InnerText = "鄭州";
            item.AppendChild(a1);
            XmlNode b1 = xml.CreateNode(XmlNodeType.Element,"adderss","");
            b1.InnerText = "鄭州大學";
            item.AppendChild(b1);
            XmlNode c1 = xml.CreateNode(XmlNodeType.Element,"time","");
            c1.InnerText = "8:30";
            item.AppendChild(c1);
            xml.Save(Server.MapPath("zrh.xml"));



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值