尝试更新XML文件,但它将所有内容放在一个标签中
本文关键字:标签 一个 文件 XML 更新 | 更新日期: 2023-09-27 18:31:08
im 尝试更新此 xml 页面:
<?xml version="1.0" encoding="utf-8"?>
<news>
<report>
<user></user>
<date></date>
<content></content>
</report>
</news>
使用此方法:
public static void InsetXML(string user, string date, string content, string Xmlfile)
{
string XMLfile;
XmlElement reportEle, userEle, dateEle, contentEle;
XmlDocument doc = new XmlDocument();
XMLfile = Xmlfile;
doc.Load(XMLfile);
reportEle = doc.CreateElement("report");
userEle = doc.CreateElement("user");
dateEle = doc.CreateElement("date");
contentEle = doc.CreateElement("content");
userEle.InnerText = user;
dateEle.InnerText = date;
contentEle.InnerText = content;
reportEle.AppendChild(userEle);
reportEle.AppendChild(dateEle);
reportEle.AppendChild(contentEle);
doc.DocumentElement.InsertAfter(reportEle, doc.DocumentElement.FirstChild);
FileStream fsxml = new FileStream(XMLfile, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
doc.Save(fsxml);
fsxml.Close();
}
考虑到,string Xmlfile = Server.MapPath("news.xml");
(从我正在使用的书中复制了该方法)但是每次我尝试它时,它都会将所有内容写入用户标签中,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<news>
<report>
<user>
</user>
<date>
</date>
<content>
</content>
</report>
<report>
<user>dsfdsfg,10.10.1999,sdfas</user>
<date>
</date>
<content>
</content>
</report>
</news>
感谢所有帮助者:D
试一试.. 我将留下此链接以供进一步参考。
public static void InsetXML(string user, string date, string content, string Xmlfile)
{
XmlDocument xmlDoc = new XmlDocument();
XmlNode rootNode = xmlDoc.CreateElement("news");
xmlDoc.AppendChild(rootNode);
XmlNode parent = xmlDoc.CreateElement("report");
rootNode.AppendChild(parent);
XmlNode child1 = xmlDoc.CreateElement("user");
child1.InnerText = user;
parent.AppendChild(child1);
XmlNode child2 = xmlDoc.CreateElement("date");
child2.InnerText = date;
parent.AppendChild(child2);
XmlNode child3 = xmlDoc.CreateElement("content");
child3.InnerText = content;
parent.AppendChild(child3);
FileStream fsxml = new FileStream(Xmlfile, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
xmlDoc.Save(fsxml);
fsxml.Close();
}
我对此进行了测试,并将XML写入了驱动器上的现有.xml文件。
结果是:
<news>
<report>
<user>dsfdsfg</user>
<date>10.10.1999</date>
<content>sdfas</content>
</report>
</news>