Vinyl Warmth
Vinyl Warmth

Reputation: 2506

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

I am trying to parse an XML RSS feed need to convert the date in an element from this:

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

to this:

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

I am able to get hold of the lastBuildDate element with the following code

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

I don't know how to get the value of the text in the element & then replace it with the correct format - can anyone help?

Upvotes: 0

Views: 1083

Answers (2)

Charles Mager
Charles Mager

Reputation: 26213

I'd suggest using LINQ to XML, it's a much nicer 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(...)

See this fiddle for a working demo.

Upvotes: 1

Display name
Display name

Reputation: 1542

This is how. I like XmlDocument. There are other ways but this will get you going.

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

Upvotes: 1

Related Questions