Below is my Sample XML File:-
I just want to replace date values with current date using LINQ to XML in C#.
Which date values? All of them? Specific elements? For example, this will replace all displayDateTime
elements with the current date - in standard XML format, which isn't what your source XML contains... if you want a different format, you should use DateTime.ToString
and replace the contents of the elements with the relevant text.
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XNamespace ns = "http://www.uk.ssp.com/SSR/XTI/Traffic/0010";
XDocument doc = XDocument.Load("ssp.xml");
var elements = doc.Descendants(ns + "displayDateTime")
.ToList();
var today = DateTime.Today;
foreach (var element in elements)
{
element.ReplaceAll(today);
}
Console.WriteLine(doc);
}
}
You could do on following manner
[Test]
public void Test()
{
XElement root = XElement.Load("Data.xml");
root.Descendants()
.Where(x => x.Name.LocalName == "displayDateTime")
.ToList()
.ForEach(x => x.ReplaceNodes(GetDate(x)));
}
private static DateTime GetDate(XElement element)
{
return DateTime.Today.Add(DateTime.Parse(element.Value).TimeOfDay);
}