C给xml文件添加带属性的父节点及子节点的方法
XML文件内容
xml操作代码示例:using System.Collections; using System.Data; using System.Xml; using System.Xml.XPath; namespace xmltest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { XML xml = new XML(Application.StartupPath + "config.xml"); string[] attstr = { "mac|08:00:27:00:D8:DC", "ip|192.168.1.1" }; string[] childstr = { "ip|192.168.1.1","name|BBQ"}; xml.AddNodes("config", "ips", attstr,childstr); } public class XML { string XMLFileName = ""; public XML(string xmlfilename) { XMLFileName = xmlfilename; } /// /// 添加一个带属性的节点,可带子节点(attstr为null时没有属性) /// /// 在哪个节点下添加新节点 /// 新节点名称 /// 新节点属性字符串数组 /// 子节点属性字符串数组 public int AddNodes(string findnodename, string creatnodename, string[] attstr, string[] childinfostr) { try { XmlDocument xml = new XmlDocument(); xml.Load(XMLFileName); XmlNode ndroot = xml.SelectSingleNode(findnodename); XmlElement nd = xml.CreateElement(creatnodename); if (attstr != null) { for (int i = 0; i < attstr.Length; i++) { string[] every = attstr[i].Split("|"); nd.SetAttribute(every[0], every[1]); } } ndroot.AppendChild(nd); if (childinfostr != null) { for (int i = 0; i < childinfostr.Length; i++) { string[] infos = childinfostr[i].Split("|"); XmlElement xe = xml.CreateElement(infos[0]); XmlText xt = xml.CreateTextNode(infos[1]); nd.AppendChild(xe); nd.LastChild.AppendChild(xt); } } xml.Save(XMLFileName); return 0; } catch (Exception ErrMsg) { return 1; } } } } }示例说明:
XML xml = new XML(Application.StartupPath + "config.xml");
//添加一个节点
string[] attstr = { "mac|08:00:27:00:D8:DC","ip|123"};
//给这个节点再添加子节点
string[] childstr = { "ip|192.168.1.1","name|BBQ"};
xml.AddNodes("config", "ips", attstr,childstr);//config是上级节点
运行结果如下:
注意:如果最后一个参数为null
xml.AddNodes("config", "ips", attstr, null);
则只添加父节点