加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:03:08 所属栏目:百科 来源:网络整理
导读: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
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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读