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

时间:2017-04-13 20:20:00

标签: c# .net xml rss xmltextreader

我正在尝试解析XML RSS feed需要转换元素中的日期:

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

我不知道如何获得元素和文本中的文本值。然后用正确的格式替换它 - 任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

这是怎么回事。我喜欢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());
            }
        }
    }
}

答案 1 :(得分:1)

我建议使用LINQ to 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