【发布时间】:2010-06-14 18:25:35
【问题描述】:
我必须序列化几个从 WebControl 继承的对象以进行数据库存储。这些包括我希望从序列化中省略的几个不必要的(对我而言)属性。例如BackColor、BorderColor等。
这是我从 WebControl 继承的一个控件的 XML 序列化示例。
<Control xsi:type="SerializePanel">
<ID>grCont</ID>
<Controls />
<BackColor />
<BorderColor />
<BorderWidth />
<CssClass>grActVid bwText</CssClass>
<ForeColor />
<Height />
<Width />
...
</Control>
我一直在尝试为我的控件创建一个公共基类,该基类继承自 WebControl,并使用“xxxSpecified”技巧选择性地选择不序列化某些属性。
例如忽略一个空的 BorderColor 属性,我希望
[XmlIgnore]
public bool BorderColorSpecified()
{
return !base.BorderColor.IsEmpty;
}
工作,但在序列化过程中从未调用过。
在要序列化的类和基类中我也试过了。
由于类本身可能会改变,我不希望必须创建自定义序列化程序。有什么想法吗?
编辑:
我已经在使用XmlAttributeOverrides,但显然不正确。我没有意识到你不能指定一个基类。我调整了我的例程,但它仍然无法正常工作。以下是我尝试过的更多细节。
我有一个名为 Activity 的 WebControl,它有一个 ContainerPanel(继承 Panel),其中包含多个 SerializePanel 类型的控件(也继承 Panel)。
尝试 1 我将 [XmlIgnore] 属性添加到 SerializePanel 的新属性没有效果。该属性仍包含在序列化中。
//This is ignored
[XmlIgnore]
public new System.Drawing.Color BackColor{
get { return base.BackColor; }
set { }}
尝试 2 我也试过SerializePanel声明中的*Specified,但是被忽略了
public bool BackColorSpecified
{
get { return !base.BackColor.IsEmpty; }
}
尝试 3 然后在序列化程序中,我传递了这里创建的覆盖:
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
string[] serPAnelProps = { "BackColor", "BorderColor", "ForeColor", "Site", "Page", "Parent", "TemplateControl", "AppRelativeTemplateSourceDirectory" };
foreach (string strAttr in serPAnelProps)
{
XmlAttributes ignoreAtrs = new XmlAttributes();
ignoreAtrs.XmlIgnore = true;
overrides.Add(typeof(SerializePanel), strAttr, ignoreAtrs);
}
string[] ignoreProps = { "Site", "Page", "Parent", "TemplateControl", "AppRelativeTemplateSourceDirectory" };
foreach (string strAttr in ignoreProps)
{
XmlAttributes ignoreAtrs = new XmlAttributes();
ignoreAtrs.XmlIgnore = true;
overrides.Add(typeof(System.Web.UI.Control), strAttr, ignoreAtrs);
}
注意:添加到 System.Web.UI.Control 类型的属性是必要的,以便能够序列化 Control。
生成的 XML sn-p 是每次尝试的结果
<Activity....>
...
<ContainerPanel>
<ID>actPnl_grAct207_0</ID>
- <Controls>
- <Control xsi:type="SerializePanel">
<ID>grCont</ID>
<Controls />
<BackColor />
<BorderColor />
<BorderWidth />
<CssClass>grActVid</CssClass>
<ForeColor />
<Height />
<Width />
<WidthUnitType>Pixel</WidthUnitType>
<HeightUnitType>Pixel</HeightUnitType>
<WidthUnit>0</WidthUnit>
<HeightUnit>0</HeightUnit>
</Control>
...
【问题讨论】:
标签: c# xml-serialization web-controls