序列化中基类字段的自定义XML元素名称
本文关键字:XML 元素 自定义 基类 字段 序列化 | 更新日期: 2023-09-27 17:58:43
在进行序列化时,如何更改从基类继承的字段的XML元素名称?
例如,我有下一个基类:
public class One
{
public int OneField;
}
序列化代码:
static void Main()
{
One test = new One { OneField = 1 };
var serializer = new XmlSerializer(typeof (One));
TextWriter writer = new StreamWriter("Output.xml");
serializer.Serialize(writer, test);
writer.Close();
}
我得到了我需要的:
<?xml version="1.0" encoding="utf-8"?>
<One xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<OneField>1</OneField>
</One>
现在,我创建了从A
继承的新类,并为其添加了额外的字段和自定义XML元素名称:
public class Two : One
{
[XmlElement("SecondField")]
public int TwoField;
}
序列化代码:
static void Main()
{
Two test = new Two { OneField = 1, TwoField = 2 };
var serializer = new XmlSerializer(typeof (Two));
TextWriter writer = new StreamWriter("Output.xml");
serializer.Serialize(writer, test);
writer.Close();
}
结果我得到了下一个输出:
<?xml version="1.0" encoding="utf-8"?>
<Two xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<OneField>1</OneField>
<SecondField>2</SecondField>
</Two>
问题是,我想在不接触基类代码的情况下将该输出中的OneField
更改为FirstField
(因为我也会使用它,并且名称必须是原始的)。我怎样才能做到这一点?
谢谢。
试试这个:
public class Two : One
{
private static XmlAttributeOverrides xmlOverrides;
public static XmlAttributeOverrides XmlOverrides
{
get
{
if (xmlOverrides == null)
{
xmlOverrides = new XmlAttributeOverrides();
var attr = new XmlAttributes();
attr.XmlElements.Add(new XmlElementAttribute("FirstField"));
xmlOverrides.Add(typeof(One), "OneField", attr);
}
return xmlOverrides;
}
}
[XmlElement("SecondField")]
public string TwoField;
}
并且您的序列化程序init要简单得多:
var xmls = new System.Xml.Serialization.XmlSerializer(typeof(Two), Two.XmlOverrides);
这里有一个解决方法:覆盖子类中的字段,并用您需要的任何名称标记覆盖字段。例如,
class One
{
public int OneField { get; set; }
}
class Two : One
{
[XmlElement("FirstField")]
public new int OneField
{
get { return base.OneField; }
set { base.OneField = value; }
}
}