C#。帮助形成XML

时间:2016-07-19 19:29:58

标签: c# xml

编辑: 好吧,终于搞定了。如果有人需要,这是我的代码

  public void Save(string savePath, string[] folderPath, string date, string time)
    {

        //path for xml
        //TODO: use "+savePath+" 
        string fileName = date+"_session.xml";

        if (File.Exists(fileName) == false)
        {
            //ID
            int sessionId = 1;


            //creating
            XDocument doc = new XDocument(
                new XElement("sessions",
                    new XElement("session",
                        new XAttribute("id", sessionId++),
                        new XAttribute("amount", folderPath.Length),
                        new XAttribute("date", date),
                        new XAttribute("time", time))));


            XElement folders = doc.Descendants("session").FirstOrDefault();
            for (int i = 0; i < folderPath.Length; i++)
            {


                folders.Add(new[] { new XElement("folderPath", folderPath[i]) });

            }


            //saving document
            doc.Save(fileName);

        } else
        {
            XDocument doc = XDocument.Load(fileName);
            int maxId = doc.Root.Elements("session").Max(t => Int32.Parse(t.Attribute("id").Value));
            XElement data = new XElement("session",
                new XAttribute("id", ++maxId),
                new XAttribute("amount", folderPath.Length),
                new XAttribute("date", date),
                new XAttribute("time", time));

            for (int i = 0; i < folderPath.Length; i++)
            {
                data.Add(new[] { new XElement("folderPath", folderPath[i]) });
            }
            doc.Root.Add(data);
            doc.Save(fileName);


        }




    }

旧代码

 public void Save(string savePath, string[] folderPath, string date, string time

我创建的程序将当前打开的文件夹保存到.txt文件中,  我正在尝试以下列方式构建XML

<?xml version="1.0" encoding="utf-8"?>
<!--This file is generated by the program.-->
<Folders>
  <Save ID="1">
  <Amount amount="3">
    <Date>19.07.2016</Date>
    <Time>22:05</Time>
	<Folder>C:\\users\test</Folder>
	<Folder>C:\\program data\\test2</Folder>
	<Folder>C:\\users\\aleksei\\desktop</Folder>
	</Amount>
  </Save>
    <Save ID="2">
  <Amount amount="2">
    <Date>19.07.2016</Date>
    <Time>23:15</Time>
	<Folder>C:\\users\test6</Folder>
	<Folder>C:\\users\\aleksei\\pictures</Folder>
	</Amount>
  </Save>
</Folders>

我想为每天生成新的xml,并且能够为一个保存会话添加多个文件夹。我现在有什么

   public void Save(string savePath, string folderPath, string date, string time, string amount)
    {
  if (File.Exists(date+"_saves.xml") == false)
        {
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Indent = true;
            xmlWriterSettings.NewLineOnAttributes = true;
            using (XmlWriter xmlWriter = XmlWriter.Create(date + "_saves.xml", xmlWriterSettings))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("Folder");

                xmlWriter.WriteStartElement("Amount", amount);
                xmlWriter.WriteElementString("Date", date);
                xmlWriter.WriteElementString("Time", time);
                xmlWriter.WriteElementString("folderPath", folderPath);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
                xmlWriter.Flush();
                xmlWriter.Close();
            }
        }
        else
        {
            XDocument xDocument = XDocument.Load(date + "_saves.xml");
            XElement root = xDocument.Element("Folder");
            IEnumerable<XElement> rows = root.Descendants("Amount");
            XElement firstRow = rows.First();
            firstRow.AddBeforeSelf(
               new XElement("Amount",
               new XElement("Date", date),
               new XElement("Time", time),
               new XElement("folderPath", folderPath)
               ));
            xDocument.Save(date + "_saves.xml");
        }
    }

2 个答案:

答案 0 :(得分:0)

这就是我喜欢创建新的xml doc

的方法
            string header = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
               "<!--This file is generated by the program.-->" +
               "<Folders></Folders>";
            XDocument doc = XDocument.Parse(header);
            XElement folders = doc.Descendants("Folders").FirstOrDefault();
            folders.Add( new[] {
               new XElement("Amount", amount),
               new XElement("Date", date),
               new XElement("Time", time),
               new XElement("folderPath", folderPath)
            });

答案 1 :(得分:0)

我通常使用以下方法使用LINQ

创建XML文档
 public static void Save(string savePath, string folderPath, string date, string time, string amount)
        {
            string count =" 3";
//I am explicitly initializing the id count but you need to query and sort in descedning order take the first id and increment accordingly
            XDocument xDocument = XDocument.Load(savePath);
            if (xDocument != null)
            {

                //To add the xml document at specific location
                xDocument.Element("Folders").Elements("Save")
                    .Where(x => x.Attribute("Id").Value == count)
                    .FirstOrDefault()
                    .AddAfterSelf(
                    new XElement("Save", new XAttribute("Id", count+1),
                new XElement("Amount", new XAttribute("amount", "3"),
                new XElement("Date", date),
                new XElement("Time", time),
                new XElement("folder", folderPath)))
                    );
                FileStream fs = new FileStream(savePath,
                               FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

                xDocument.Save(fs);

            }

            else
            {
                //If folder is open and xml file doesnt exist
                XDocument newDocument = new XDocument(
              new XDeclaration("1.0", "utf-8", "yes"),
               new XComment("This file is generated by the program."),
                //Root single Element              
                new XElement("Folders",

                //child Elements
                new XElement("Save", new XAttribute("Id", "1"),
                new XElement("Amount", new XAttribute("amount", "3"),
                new XElement("Date", date),
                new XElement("Time", time),
                new XElement("folder", folderPath)))
                ));

                FileStream fs = new FileStream(savePath,
                               FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

                     newDocument.Save(fs);

            }

在这里,您需要查询现有的xml文档中的ID属性,并按降序排列,然后如果有打开的文件夹,请在此ID之后添加新节点。