LINQ TO XML, How to replace values with new values c#

后端 未结 2 1151
温柔的废话
温柔的废话 2021-01-15 01:38

Below is my Sample XML File:-

I just want to replace date values with current date using LINQ to XML in C#.



        
相关标签:
2条回答
  • 2021-01-15 02:02

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-15 02:03

    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);
        }
    
    0 讨论(0)
提交回复
热议问题