如何使用 C# 替换 Xml 字符串中的日期?

How can I replace a date in an Xml string using C#?

我正在尝试解析一个 XML RSS 提要,需要从这个元素中转换日期:

<lastBuildDate>Thu, 13 Apr 2017</lastBuildDate>

对此:

<lastBuildDate>Thu, 13 Apr 2017 09:00:52 +0000</lastBuildDate>

我可以使用以下代码获取 lastBuildDate 元素

XmlTextReader reader = new XmlTextReader(rssFeedUrl);
while (reader.Read())
{
  if (reader.NodeType == XmlNodeType.Element && reader.Name.Contains("BuildDate"))
  {
    // replace DateTime format
  }
}

我不知道如何获取元素中文本的值,然后将其替换为正确的格式 - 谁能帮忙?

是这样的。我喜欢 XmlDocument。还有其他方法,但这会让你继续。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ConsoleApplication1
{
    class Program
    {
    public static void Main()
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<?xml version='1.0' encoding='UTF-8' standalone='no'?><root><lastBuildDate>Thu, 13 Apr 2017</lastBuildDate></root>");

            XmlNodeList list = doc.GetElementsByTagName("lastBuildDate");

            foreach(XmlNode node in list )
            {
                DateTime result = new DateTime();
                if (DateTime.TryParse(node.InnerXml, out result))
                {
                    node.InnerText = result.ToString("ddd, d MMM yyyy HH:mm:ss") + "+0000"; //Thu, 13 Apr 2017 09:00:52 +0000
                }
            }
            using (var stringWriter = new StringWriter())
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
                doc.WriteTo(xmlTextWriter);
                xmlTextWriter.Flush();
                Console.Write(stringWriter.GetStringBuilder().ToString());
            }
        }
    }
}

我建议使用 LINQ 来 XML,它更好 API:

var doc = XDocument.Load(rssFeedUrl);

var lastBuildDate = doc.Descendants("lastBuildDate").Single();

var lastBuildDateAsDateTime = (DateTime) lastBuildDate;

lastBuildDate.Value = "new value here"; // perhaps based on lastBuildDateAsDateTime above

// get XML string with doc.ToString() or write with doc.Save(...)

有关工作演示,请参阅 this fiddle