Search code examples
c#xmlserializationlinq-to-xmlconfigurationsection

Add, Remove, Modify XML nodes without re-writting/overwritting entire XML file with Serializable objects


I am looking for workaround to write only "modified objects" to file without overwriting existing nodes/elements. I know how to Serialize object to XML using XmlSerializer class, but this involves re-writing entire XML.

Also, How is it possible with ConfigurationSection, ConfigurationElement classes of System.Configuration namespace?

So far, I have tried below code:

    // <summary>This method serializes the contents of the current object to the specified file</summary>
    /// <param name="fileName">The file name</param>
    /// <returns>True if the serialize was successful</returns>
    private bool SerializeObjectToFile(string fileName)
    {
        bool retVal = false;

        try
        {
            using (Stream fStream =
                new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                //'UserDataObject ' is the class which I want to serialize
                (new XmlSerializer(typeof(UserDataObject))).Serialize(fStream, this);

                retVal = true;
            }
        }
        catch (Exception ex)
        {
            // Error
            //LogObj.Logger.WriteTrace("Exception=" + ex.Message);
        }

        return retVal;
    }

sample XML format as below:

<?xml version="1.0"?>
<UserDataObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <ExistingItems>
        <LocalObject>
            <Name>FirstObject</Name>
            :
        </LocalObject>
        :
     </ExistingItems>

     <NewItems>
        <MyNewObject>
            <User>Admin</User>
            <LastConnected>9/6/2017 4:00PM</LastConnected>
            :
        </MyNewObject>
        :
     </NewItems>
    </UserDataObject>

Does anyone knows how to insert/update only particular <section> or <element> of existing XML?

Thanks!


Solution

  • I managed to implement it with below class, which is available in .NET. If anyone has better way to do it.. would be interested to know.:)

    How to: Create Custom Configuration Sections Using ConfigurationSection