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;
}
/// <summary>
/// 添加一个带属性的节点,可带子节点(attstr为null时没有属性)
/// </summary>
/// <param name="findnodename">在哪个节点下添加新节点</param>
/// <param name="creatnodename">新节点名称</param>
/// <param name="attstr">新节点属性字符串数组</param>
/// <param name="childinfostr">子节点属性字符串数组</param>
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是上级节点
运行结果如下:
xml.AddNodes("config", "ips", attstr, null);
则只添加父节点