[英]LINQ TO XML, How to replace values with new values c#
Below is my Sample XML File:- 以下是我的示例XML文件:
I just want to replace date values with current date using LINQ to XML in C#. 我只想在C#中使用LINQ to XML将日期值替换为当前日期。
<?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. 例如,这会将所有
displayDateTime
元素替换为当前日期-标准XML格式,而不是您的源XML包含的格式...如果您希望使用其他格式,则应使用DateTime.ToString
并替换其中的内容元素以及相关文字。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.