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

后端 未结 2 1178
温柔的废话
温柔的废话 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条回答
  •  猫巷女王i
    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);
        }
    }
    

提交回复
热议问题