添加、删除、修改 XML 节点,而无需使用可序列化对象重写/覆盖整个 XML 文件



我正在寻找解决方法,仅将"修改的对象"写入文件而不覆盖现有节点/元素。我知道如何使用XmlSerializerSerialize XML 的对象,但这涉及重写整个 XML。

另外,ConfigurationSectionConfigurationElement System.Configuration命名空间的类怎么可能?

到目前为止,我已经尝试了以下代码:

    // <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;
    }

示例 XML 格式如下所示:

<?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>

有谁知道如何插入/更新现有XML的特定<section><element>

谢谢!

我设法用下面的类实现它,它在 .NET 中可用。如果有人有更好的方法去做..有兴趣知道.:)

如何:使用配置节创建自定义配置节

最新更新