如何创建多个xml文件并对其进行日期标记?

时间:2016-08-10 14:35:14

标签: c# .net xml

此应用程序向返回数据的API发送请求。我想将该数据保存到xml文件。 问题是,每次运行应用程序时,我都想创建一个新的xml文件,而不是替换当前的“c:\ temp \ xml.xml”。我希望它们能够按当前日期命名,而不是1 xml.xml我想要20160810.xml,第二天当我运行应用程序时,我想要另一个名为20160811.xml的xml文件。我该怎么做?

    static void Main(string[] args)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            //Send HTTPrequest
            client.BaseAddress = new Uri("http://xxxxx");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/people/peoples?Firstname=Adam");

            if (response.IsSuccessStatusCode)
            {
                var person = response.Content.ReadAsAsync<IEnumerable<Persons>>().Result;

                XmlDocument xmldoc = new XmlDocument();
                foreach (var i in person)
                {
                    XmlElement el = (XmlElement)xmldoc.AppendChild(xmldoc.CreateElement("Employee"));
                    el.SetAttribute("EmployeeID", i.Peopleid);
                    el.AppendChild(xmldoc.CreateElement("Firstname")).InnerText = i.FirstName;
                    el.AppendChild(xmldoc.CreateElement("Lastname")).InnerText = i.LastName;
                    el.AppendChild(xmldoc.CreateElement("Address")).InnerText = i.LocationName;

                    Console.WriteLine("{0}\t{1}:\t{2}\t-{3}", i.FirstName, i.LastName, i.Peopleid, i.LocationName );
                    xmldoc.Save("c:\\temp\\xml.xml");
                }

            }
        }


    }

class Persons
{
    public string Peopleid { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string LocationName { get; set; }


}

1 个答案:

答案 0 :(得分:0)

DateTime.Now提供当前日期和时间,因此请将保存修改为

xmldoc.Save("c:\\temp\\"+DateTime.Now.ToString("yyyyMMdd") + ".xml");