[英]De-serialize derived type
我以為我終於了解了XmlSerialization,但是我的最后一種方法讓我覺得自己像是一個新手。 我的意圖是創建一個可以對某種配置進行序列化和反序列化的框架。 因此,我創建了一個配置類,如下所示:
/// <summary>
/// Application-wide configurations that determine how to transform the features.
/// </summary>
[XmlRoot(Namespace = "baseNS")]
public class Config
{
/// <summary>
/// List of all configuration-settings of this application
/// </summary>
[System.Xml.Serialization.XmlElement("Setting")]
public List<Setting> Settings = new List<Setting>();
}
現在,我需要某種配置,該配置定義了一個自定義設置列表。
/// <summary>
/// Application-wide configurations that determine how to transform the features.
/// </summary>
[System.Xml.Serialization.XmlRoot("Config", Namespace = "baseNS")]
[System.Xml.Serialization.XmlInclude(typeof(BW_Setting))]
public class BW_Config : Config {
// nothing to add, only needed to include type BW_Setting
}
/// <summary>
/// Provides settings for one single type of source-feature specified by the <see cref="CQLQuery"/>-property. Only one target-featureType is possible for every setting.
/// However settings for different targetTypes may have the same source-type provided.
/// </summary>
[System.Xml.Serialization.XmlRoot("Setting", Namespace = "anotherNS")]
public class BW_Setting : Setting {
// add and modify some attributes
}
據我所知,我將XmlInclude屬性放在基類上(正在設置)。 因此,Setting和BW_Setting駐留在不同的程序集中,而后者取決於前者,因此我無法使用此方法,因為我會得到一個圓參考。
這是實際的序列化器的代碼:
XmlSerializer ser = new XmlSerializer(typeof(BW_Config));
BW_Config c = new BW_Config();
c.Settings.Add(new BW_Setting());
((BW_Setting)c.Settings[0]).CQLQuery = "test";
現在,當執行上述操作時,我得到錯誤消息: "Type BW_Setting was not expected. Use XmlInclude..."
我可能會更改自定義程序"Type BW_Setting was not expected. Use XmlInclude..."
所有內容,但是基類屬於該框架,因此我無法更改它。 您可以幫助我進行序列化(和反序列化)工作嗎?
我終於通過定義一些覆蓋使其工作:
// determine that the class BW_Setting overrides the elements within "Settings"
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(
typeof(Config),
"Settings", new XmlAttributes {
XmlElements = {
new XmlElementAttribute("Setting", typeof(BW_Setting)) } });
XmlSerializer ser = new XmlSerializer(typeof(Config), overrides);
這將產生以下輸出
<?xml version="1.0"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="baseNS">
<Setting id="0">
<CQLQuery>test</CQLQuery>
</Setting>
</Config>
唯一不愉快的是,標記設置的XML中的名稱空間丟失了。 但是反序列化也可以,因此並不那么令人討厭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.