XML仍然为空
本文关键字:XML | 更新日期: 2023-09-27 18:13:04
这可能是一个非常愚蠢的问题,但我似乎不能让这个东西工作。我正在尝试使用以下结构形成XML,并且能够在任何时间点向其中添加额外的数据,以及读取数据。现在我得到的是:
<?xml version="1.0" encoding="utf-8"?>
<sessions />
What I want
<?xml version="1.0" encoding="utf-8"?>
<sessions>
<session date="14.10.2016" time="17:15" amount="3">
<folder>C:''Users</folder>
<folder>C:''Test</folder>
<folder>C:''Asgbsf''Aleksei</folder>
</session>
<sessions />
My c# code
static void Main(string[] args)
{
createXML();
Console.WriteLine("Test XML");
folderList.Add("C:''Users");
folderList.Add("C:''Test");
folderList.Add("C:''Asgbsf''Aleksei");
XML();
Console.ReadKey();
}
static List<String> folderList = new List<String>();
private static string generateRandom(int min, int max)
{
Random rnd = new Random();
return rnd.Next(min, max).ToString();
}
public static string pathToXml = "test_aleksei2.xml";
public static void createXML()
{
XmlTextWriter textWritter = new XmlTextWriter(pathToXml, Encoding.UTF8); //Creating file
textWritter.WriteStartDocument(); //XML header
textWritter.WriteStartElement("sessions"); //XML head
textWritter.WriteEndElement(); //end writing element
textWritter.Close(); //close XmlTextWriter
}
public static void XML()
{
Console.WriteLine("XML function being executed");
XmlDocument document = new XmlDocument(); //using XmlDocument to Read
document.Load(pathToXml); //loading XML
XmlNode element = document.CreateElement("session"); //parent element
XmlAttribute date = document.CreateAttribute("date"); //creating attribute
date.Value = "14.10.2016";
element.Attributes.Append(date); //append attribute to element
XmlAttribute time = document.CreateAttribute("time");
time.Value = generateRandom(0, 23) + ":" + generateRandom(1, 59);
element.Attributes.Append(time);
XmlAttribute amount = document.CreateAttribute("amount");
amount.Value = generateRandom(1, 10);
element.Attributes.Append(amount);
XmlNode folder = null;
for (int i = 0; i < folderList.Count; i++)
{
Console.WriteLine(folderList[i]+" - " + i + "/" + folderList.Count);
folder = document.CreateElement("Folder");
folder.InnerText = folderList[i];
element.AppendChild(folder);
}
document.Save(pathToXml);
}
请帮帮我,我不明白我做错了什么。如果我只是c&p,我可能甚至不知道这里的问题是什么……提前谢谢大家
在您的XML方法中,您在创建文档之后从未将session
元素附加到文档中。因此,即使您创建并添加了所有这些子元素到元素中,它们都不会被添加到文档中。
您需要在保存文档之前添加这一行:
document.DocumentElement.AppendChild(element);