{
StringBuilder xmlAccount = new StringBuilder();
if (!File.Exists(url))//判断是否存在,创建xml文档
{
xmlAccount.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
xmlAccount.Append("<accountlist>");
xmlAccount.Append("<account>");
xmlAccount.AppendFormat("<accountName>{0}</accountName>",Account);
xmlAccount.AppendFormat("<accountPwd>{0}</accountPwd>",pwd);
xmlAccount.AppendFormat("<accountTime>{0}</accountTime>",DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
xmlAccount.Append("</account>");
xmlAccount.Append("</accountlist>");
StreamWriter sw = new StreamWriter(url);
sw.WriteLine(xmlAccount);
sw.Close();
}
else
{
using (StreamWriter SW = File.AppendText(url))
{
SW.Close();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);
XmlNode node = xmlDoc.SelectSingleNode("accountlist");
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (node.ChildNodes[i].ChildNodes[0].InnerText == Account)//判断是否有重名的Account
{
node.ChildNodes[i].ParentNode.RemoveChild(node.ChildNodes[i]);//移出当前节点的子节点
}
}
XmlElement childnode = xmlDoc.CreateElement("account");
node.PrependChild(childnode);
XmlElement childnodeName = xmlDoc.CreateElement("accountName");
XmlElement childnodePwd = xmlDoc.CreateElement("accountPwd");
childnodePwd.InnerText = pwd;
childnodeName.InnerText = Account;
xmlDoc.Save(url);
XmlElement childnodeTime = xmlDoc.CreateElement("accountTime");
childnodeTime.InnerText = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
childnode.AppendChild(childnodeName);
childnode.AppendChild(childnodePwd);
childnode.AppendChild(childnodeTime);
xmlDoc.Save(url);
StreamWriter sw = File.AppendText(url);
sw.WriteLine(xmlAccount);
sw.Close();
}
}
具体效果,如下图所示,读取这个文件的时候这样写:XmlDocument xml = new XmlDocument();
xml.Load(url);
xml的api
http://www.cnblogs.com/kissdodog/archive/2013/02/24/2924236.html
想看的童鞋们可以自己看哦