C#, insert strongly typed object into XML Document as Element

cxml

I have an XML document that contains the following structure:

Its more or less a collection of Events:

<Events>
  <Event>
    <DateTime></DateTime>
    <EventType></EventType>
    <Result></Result>
    <Provider></Provider>
    <ErrorMessage></ErrorMessage>
    <InnerException></InnerException>
  </Event>
</Events>

In C# I have a persistent object called Event:

Now given that the document already exists, and saved to file… I call :

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(dataPath);

Now how can I add a new Event item to events?

I've got a strongly typed Event item in my C# code, and want it inserted into the Events collection in the XML object as last child.

I guess this is what I am really asking : https://stackoverflow.com/questions/1457033/c-insert-a-strongly-typed-object-as-node-in-existing-xml-document

Best Answer

Take a look at the Xml Serialization attributes.

You can do this:

[XmlRoot("Event")]
public class Event
{

    [XmlElement("DateTime")]
    public string DateTime 
    {
        get;
        set;
    }

    [XmlElement("EventType")]
    public EnumReportingEventType EventType
    {
        get;
        set;
    }

    [XmlElement("Result")]
    public EnumReportingResult Result
    {
        get;
        set;
    }

    [XmlElement("Provider")]
    public string Provider
    {
        get;
        set;
    }

    [XmlElement("ErrorMessage")]
    public string ErrorMessage
    {
        get;
        set;
    }

    [XmlElement("InnerException")]
    public string InnerException
    {
        get;
        set;
    }
}

In fact, if the properties of your class have the same name as the elements in your Xml, you do not have to use the XmlElement attributes.

Then, you can use the XmlSerializer to serialize and deserialize.

Edit: Then, wouldn't it be better to create a type which represent the entire type that is stored in the existing xml ?
Deserialize it, give a value to the additional property, and serialize it back ?