Click here to Skip to main content
16,015,594 members
Articles / General Programming / File
Tip/Trick

Read/Edit datetime Field on a XML File

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
21 Jan 2015CPOL1 min read 26K   6   4
Read XML File and change date contents

Introduction

I had a simple requirement yesterday to read an XML file, change a date field and save. This was a very simple task, but I had to refresh my XML basics and figure out how to change its contents which still took me an hour. There seem to be hundreds of web posts on XML reader issues, resolution, and altenatives but I wanted to post my simple method on doing this. I wrote 2 overloaded methods. The first takes a file name string parameter and simply reads XML file to return date value from an element. The second takes file name string and datetime parameter, changes the required field in XML file and save.

Using the Code

Here is the XML file:

XML
<?xml version="1.0" encoding="utf-8"?>
<ROOT>
  <CLASS PROCESSINGDATE="20152101" CLASSID="6">
    <FIELD FLDDATA="1" FLDNAME="CLASSTYPE" />
    <FIELD FLDDATA="2" FLDNAME="CLASSTYPECODE" />
    <FIELD FLDDATA="3" FLDNAME="CLASSTYPESUBCODE" />
  </CLASS>
</ROOT>

<CLASS> = element

<PROCESSINGDATE> = attribute

<FIELD> = sub-element

In another method, ProcessingDateTime field is read as string from XML file so it is converted to standard date format.

C#
retProcDate = Convert.ToDateTime(pdate.Substring(4, 2) + "/" + 
        pdate.Substring(6, 2) + "/" + pdate.Substring(0, 4));

For the first requirement, date had to be formatted as yyyyMMdd before saving.

In order to access other fields/attributes of the class element, simply change to ["CLASSID"].Value.

C#
xd.DocumentElement.FirstChild.Attributes["PROCESSINGDATE"].Value = 
                String.Format("{0:yyyyMMdd}", dtProcDate);

Here is a great reference site when working with String Format for DateTime.

http://www.csharp-examples.net/string-format-datetime/

Here is the full code:

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

namespace ReadXMLDate
{
    class Program
    {
        static void Main(string[] args)
        {
            const string FName = "C:\\Class.xml";
            DateTime NewDate = DateTime.Now;
            ReadDateFromXML(FName, NewDate);
        NewDate = ReadDateFromXML(FName);
        }

        private static void ReadDateFromXML(string filename, DateTime dtProcDate)
        {
            if (File.Exists(filename))
            {
                XmlDocument xd = new XmlDocument();
                xd.Load(filename);

                xd.DocumentElement.FirstChild.Attributes["PROCESSINGDATE"].Value = 
                        String.Format("{0:yyyyMMdd}", dtProcDate);
                xd.Save(filename);
            }
        }

        private static DateTime ReadDateFromXML(string filename)
        {
            DateTime retProcDate = new DateTime();
            if (File.Exists(filename))
            {
                XmlDocument xd = new XmlDocument();
                xd.Load(filename);

                string pdate = xd.DocumentElement.FirstChild.Attributes["PROCESSINGDATE"].Value;
                if (!string.IsNullOrEmpty(pdate))
                {
                    retProcDate = Convert.ToDateTime
            (pdate.Substring(4, 2) + "/" + pdate.Substring(6, 2) + "/" + 
            pdate.Substring(0, 4));
                }
            }
            return retProcDate;
        }
    }
}

Points of Interest

Before I was using XmlReader but encountered this error when trying to read the file.

C#
XmlReader xmlReader = XmlReader.Create(new StringReader(filename));
while (xmlReader.Read())

XmlReader wasn't loading and encountered unhandled XmlException.

Data at the root level is invalid. Line 1, position 1.

Instead of chasing it, I used XML Load property which worked without any issues.

History

No updates yet. Suggestions are welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionThere's a standard for Date and Time encoded as string Pin
sx200825-Jan-15 3:58
sx200825-Jan-15 3:58 
GeneralRe: There's a standard for Date and Time encoded as string Pin
Bhis27-Jan-15 5:18
Bhis27-Jan-15 5:18 
SuggestionDate format not standard. Pin
the Kris23-Jan-15 2:35
the Kris23-Jan-15 2:35 
It was probably not up to you but I don't understand why people do not stick to a standard for XML data fields.

XSD Date and Time Data Types

BTW: the example contains "20152101" but you define the format as "yyyyMMdd".

Thanks for sharing though.

modified 23-Jan-15 9:05am.

GeneralRe: Date format not standard. Pin
Bhis23-Jan-15 6:34
Bhis23-Jan-15 6:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.