1

I want to transfer a variable containing DateTime string to the XML file. Is there any way to access data from C# Class in XML File.

Here's my C# Code:

DateTime dt = DateTime.Today.AddHours(17);
string datetime = dt.ToString("yyyy-MM-ddTHH:mm:ss");

Here's my XML Code where I need to access this data string:

<ProductLastModifiedDate>2020-02-21T09:00:00+05:30</ProductLastModifiedDate>

In the above XML Code I want to set dateTime retrieved from C# class file.

0

2 Answers 2

1

Use xml linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace XML
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            DateTime dt = DateTime.Today.AddHours(17);
            string datetime = dt.ToString("yyyy-MM-ddTHH:mm:ss");

            XDocument doc = XDocument.Load(FILENAME);

            XElement date = doc.Descendants("ProductLastModifiedDate").FirstOrDefault();
            date.SetValue(datetime);
            doc.Save(FILENAME);

        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Another approach is using XmlDocument

DateTime dt = DateTime.Today.AddHours(17);
string datetime = dt.ToString("yyyy-MM-ddTHH:mm:ss");

var xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
xmlDoc.SelectSingleNode("ProductLastModifiedDate").InnerText = datetime;            
xmlDoc.Save(filePath);

OUTPUT

<ProductLastModifiedDate>2020-02-20T17:00:00</ProductLastModifiedDate>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.