上次操作这东西还是第一个项目里面,为了读取xml文件里面的大量的数据操作这东西。
现在突然要写这东西虽然很简单,还是有点生疏,写个demo以备查阅。后面再linq to xml就简单很多。
使用的xml文件demo.xml:
<?xml version="1.0" encoding="utf-8"?> <connectionstrings> <connectionstring id="connstr1"> <serverAddress>127.0.0.1</serverAddress> <dataBase>test</dataBase> <userId>sa</userId> <password>111222</password> </connectionstring> <connectionstring id="connstr2"> <serverAddress>127.0.0.1</serverAddress> <dataBase>test</dataBase> <userId>sa</userId> <password>111222</password> </connectionstring> </connectionstrings>
然后是操作xml的类XmlOperatorDemo.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace TestDemo { public class XmlOperateDemo { readonly XmlDocument xmlDoc=new XmlDocument(); private readonly string xmlPath = ""; public XmlOperateDemo(string xmlpath) { xmlDoc.Load(xmlpath); xmlPath = xmlpath; } public void GetNodeValue() { var list = xmlDoc.GetElementsByTagName("connectionstring");//获取节点列表 foreach (XmlElement xe in list) { Console.WriteLine(xe.GetAttribute("id")+":");//获取属性 Console.WriteLine(xe.InnerXml);//节点内容 XmlElement address = (XmlElement)xe.SelectSingleNode("serverAddress");//获取节点 Console.WriteLine("serverAddress:" + address.InnerText); } } public void SetNodeValue() { var nodecount = xmlDoc.GetElementsByTagName("connectionstring").Count+1; var connstr3 = xmlDoc.CreateElement("connectionstring"); connstr3.SetAttribute("id", "connstr" + nodecount);//设置属性 XmlElement serverAddress = xmlDoc.CreateElement("serverAddress"); serverAddress.InnerText = "127.0.0.1";//设置文本内容 XmlElement dataBase = xmlDoc.CreateElement("dataBase"); dataBase.InnerText = "test"; XmlElement userId = xmlDoc.CreateElement("userId"); userId.InnerText = "sa"; XmlElement password = xmlDoc.CreateElement("password"); password.InnerText = "111222"; connstr3.AppendChild(serverAddress); connstr3.AppendChild(dataBase); connstr3.AppendChild(userId); connstr3.AppendChild(password); Console.WriteLine("---new connstr---:"); Console.WriteLine(connstr3.InnerXml); var root= xmlDoc.SelectSingleNode("connectionstrings");//根节点 root.AppendChild(connstr3);// 添加节点 xmlDoc.Save(xmlPath);//保存 Console.WriteLine("after nodeadding:"); GetNodeValue(); } public void DeleteNode() { Console.WriteLine("before delete-----------------------:"); GetNodeValue(); var root = xmlDoc.SelectSingleNode("connectionstrings"); var node=root.SelectSingleNode("connectionstring");
//删除节点 root.RemoveChild(node); xmlDoc.Save(xmlPath); Console.WriteLine("after delete-----------------------:"); GetNodeValue(); } } }
测试主方法:
static void Main(string[] args) { var xmldemo=new XmlOperateDemo(@"D:\visual studio\TestDemo\TestDemo\demo.xml"); //xmldemo.GetNodeValue(); //xmldemo.SetNodeValue(); xmldemo.DeleteNode(); Console.Read(); }