///////创建XML
private void button1_Click(object sender, EventArgs e)
{
string strIMEI = "11111111";
try
{
//创建XmlDocument对象
XmlDocument doc = new XmlDocument();
//创建Xml节点
XmlNode xmlNode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
doc.AppendChild(xmlNode);
//创建元素
XmlElement xelement = doc.CreateElement("", "body", "");
doc.AppendChild(xelement);
XmlNode node = doc.SelectSingleNode("body");
//设备元素
XmlElement element = doc.CreateElement("item");
element.SetAttribute("IMEI", strIMEI);
node.AppendChild(element);
//得到当前应用程序所在目录
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
doc.Save(path + "//config.xml");
}
catch (Exception ea)
{
MessageBox.Show(ea.Message.ToString());
}
}
============================================
//添加节点
private void button2_Click(object sender, EventArgs e)
{
//添加节点
XmlDocument xmlDoc = new XmlDocument();
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
xmlDoc.Load(path + @"/config.xml");
XmlNode node = xmlDoc.SelectSingleNode("body");
XmlElement element = xmlDoc.CreateElement("username");
element.SetAttribute("name", "aaaaa");
node.AppendChild(element);
xmlDoc.Save(path + "//config.xml");
}
=================================================
//显示节点
private void button3_Click(object sender, EventArgs e)
{
//显示节点
XmlDocument xmlDoc = new XmlDocument();
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
xmlDoc.Load(path + @"/config.xml");
XmlNode node = xmlDoc.SelectSingleNode("body/item");
this.textBox1.Text = node.Attributes[0].InnerText.ToString();
//((System.Xml.XmlAttribute)((new System.Collections.ArrayList.ArrayListDebugView(((System.Xml.XmlNamedNodeMap)(((System.Xml.XmlElement)(node)).Attributes.System.Collections.ICollection.SyncRoot)).nodes)).Items[0])).Value;// node.Value.ToString();
}
==================================================
//更新节点
private void button4_Click(object sender, EventArgs e)
{
//更新节点
XmlDocument xmlDoc = new XmlDocument();
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
xmlDoc.Load(path + @"/config.xml");
XmlNodeList list = xmlDoc.SelectSingleNode("body").ChildNodes;
foreach (XmlNode node in list)
{
XmlElement ea = (XmlElement)node;
if (ea.GetAttribute("IMEI") != "333333")
{
ea.SetAttribute("IMEI","333333");
}
}
//string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
xmlDoc.Save(path + "//config.xml");
}