简体   繁体   中英

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

Below is my Sample XML File:-

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

<?xml version="1.0" encoding="UTF-8"?>
<BasicImport xmlns="http://www.uk.SSp.com/SSR/XTI/Traffic/0010" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.uk.nds.com/SSR/XTI/Traffic/0010 0010.xsd" utcOffset="+05:30" frameRate="25">
  <SiEventSchedule deleteStart="2012/01/21 00:00:00" deleteEnd="2012/01/21 23:59:59">
    <siService>Ssp</siService>
    <playoutSource>Ssp</playoutSource>
    <activationSourceId>0</activationSourceId>
    <CaSchedule deleteStart="2012/01/21 00:00:00" deleteEnd="2012/01/21 23:59:59" />
    <SiEvent>
      <displayDateTime>2012/01/21 00:00:00</displayDateTime>
      <activationDateTime>2012/01/21 00:00:00</activationDateTime>
      <displayDuration>00:30:00</displayDuration>
      <siTrafficKey>056049263</siTrafficKey>
      <detailKey>056049263 2012-07-12</detailKey>
     </SiEvent>
   </SiEventSchedule>
</BasicImport>

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM