动态生成xml文贱,并动态添加节点,每次追加

前端之家收集整理的这篇文章主要介绍了动态生成xml文贱,并动态添加节点,每次追加前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public void AddLog(string Account,string url,string pwd)//url为文件地址,即文件路径
{
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

想看的童鞋们可以自己看哦

猜你在找的XML相关文章