0

How can I read the following xml file into a List:

Partial XML file (data.log)

<ApplicationLogEventObject>
    <EventType>Message</EventType>
    <DateStamp>10/13/2016 11:15:00 AM</DateStamp>
    <ShortDescription>N/A</ShortDescription>
    <LongDescription>Sending 'required orders' email.</LongDescription>
</ApplicationLogEventObject>
<ApplicationLogEventObject>
    <EventType>Message</EventType>
    <DateStamp>10/13/2016 11:15:10 AM</DateStamp>
    <ShortDescription>N/A</ShortDescription>
    <LongDescription>Branches Not Placed Orders - 1018</LongDescription>
</ApplicationLogEventObject>
<ApplicationLogEventObject>
    <EventType>Message</EventType>
    <DateStamp>10/13/2016 11:15:10 AM</DateStamp>
    <ShortDescription>N/A</ShortDescription>
    <LongDescription>Branches Not Placed Orders - 1019</LongDescription>
</ApplicationLogEventObject>
...

And here is the data access layer (DAL):

public List<FLM.DataTypes.ApplicationLogEventObject> Get()
    {
        try
        {
            XmlTextReader xmlTextReader = new XmlTextReader(@"C:\data.log");
        List<FLM.DataTypes.ApplicationLogEventObject> recordSet = new List<ApplicationLogEventObject>();

        xmlTextReader.Read();

        while (xmlTextReader.Read())
        {
            xmlTextReader.MoveToElement();
            FLM.DataTypes.ApplicationLogEventObject record = new ApplicationLogEventObject();

            record.EventType = xmlTextReader.GetAttribute("EventType").ToString();
            record.DateStamp = Convert.ToDateTime(xmlTextReader.GetAttribute("DateStamp"));
            record.ShortDescription = xmlTextReader.GetAttribute("ShortDescription").ToString()                    
            record.LongDescription = xmlTextReader.GetAttribute("LongDescription").ToString();

            recordSet.Add(record);
        }
        return recordSet;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

And the Data Types which will hold the child elements from the XML file:

public class ApplicationLogEventObject
{
    public string EventType { get; set; }
    public DateTime DateStamp { get; set; }
    public string ShortDescription { get; set; }
    public string LongDescription { get; set; }
}

After I've read the child nodes into a List I would then like to return it and display it in a DataGridView.

Any help regarding this question will be much appreciated.

rene
  • 41,474
  • 78
  • 114
  • 152
Tim Kruger
  • 863
  • 2
  • 10
  • 26

1 Answers1

3

Your log file is not an XML document. Since an XML document must have one and only one root element, it's a series of XML documents concatenated together. Such a series of documents can be read by XmlReader by setting XmlReaderSettings.ConformanceLevel == ConformanceLevel.Fragment. Having done so, you can read through the file and deserialize each root element individually using XmlSerializer as follows:

static List<ApplicationLogEventObject> ReadEvents(string fileName)
{
    return ReadObjects<ApplicationLogEventObject>(fileName);
}

static List<T> ReadObjects<T>(string fileName)
{
    var list = new List<T>();

    var serializer = new XmlSerializer(typeof(T));
    var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
    using (var textReader = new StreamReader(fileName))
    using (var xmlTextReader = XmlReader.Create(textReader, settings))
    {
        while (xmlTextReader.Read())
        {   // Skip whitespace
            if (xmlTextReader.NodeType == XmlNodeType.Element) 
            {
                using (var subReader = xmlTextReader.ReadSubtree())
                {
                    var logEvent = (T)serializer.Deserialize(subReader);
                    list.Add(logEvent);
                }
            }
        }
    }

    return list;            
}

Using the following version of ApplicationLogEventObject:

public class ApplicationLogEventObject
{
    public string EventType { get; set; }

    [XmlElement("DateStamp")]
    public string DateStampString { 
        get
        {
            // Replace with culturally invariant desired formatting.
            return DateStamp.ToString(CultureInfo.InvariantCulture);
        }
        set
        {
            DateStamp = Convert.ToDateTime(value, CultureInfo.InvariantCulture);
        }
    }

    [XmlIgnore]
    public DateTime DateStamp { get; set; }

    public string ShortDescription { get; set; }
    public string LongDescription { get; set; }
}

Sample .Net fiddle.

Notes:

  • The <DateStamp> element values 10/13/2016 11:15:00 AM are not in the correct format for dates and times in XML, which is ISO 8601. Thus I introduced a surrogate string DateStampString property to manually handle the conversion from and to your desired format, and then marked the original DateTime property with XmlIgnore.

  • Using ReadSubtree() prevents the possibility of reading past the end of each root element when the XML is not indented.

  • According to the documentation for XmlTextReader:

    Starting with the .NET Framework 2.0, we recommend that you use the System.Xml.XmlReader class instead.

    Thus I recommend replacing use of that type with XmlReader.

  • The child nodes of your <ApplicationLogEventObject> are elements not attributes, so XmlReader.GetAttribute() was not an appropriate method to use to read them.

  • Given that your log files are not formatting their times in ISO 8601, you should at least make sure they are formatted in a culturally invariant format so that log files can be exchanged between computers with different regional settings. Doing your conversions using CultureInfo.InvariantCulture ensures this.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • Awesome thanks very much for the code and explanation dbc, appreciate it. – Tim Kruger Sep 28 '17 at 19:20
  • I just want to test the code out this weekend, or early next week and if it has answered my question, which looking at your code it does seem like it should, I'll definitely mark your answer as the solution to my problem ;-). – Tim Kruger Sep 29 '17 at 13:26