我正在寻找解决方法,仅将"修改的对象"写入文件而不覆盖现有节点/元素。我知道如何使用XmlSerializer
类Serialize
XML 的对象,但这涉及重写整个 XML。
另外,ConfigurationSection
、ConfigurationElement
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 中可用。如果有人有更好的方法去做..有兴趣知道.:)
如何:使用配置节创建自定义配置节