序列化中基类字段的自定义XML元素名称 [英] Custom XML-element name for base class field in serialization
问题描述
如何在进行序列化时更改从基类继承的字段的XML元素名称?
How can I change XML-element name for field inherited from base class while doing serialization?
例如,我有下一个基类:
For example I have next base class:
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();
}
我得到了我需要的东西:
I get what I need:
<?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元素名称:
Now I have created new class inherited from A
with additional field and custom XML element name for it:
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();
}
结果我得到下一个输出:
As a result I get next output:
<?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
而不触及基类代码(因为我也会使用它,名称必须是原始的)。我怎么能做到这一点?
The problem is that I want to change OneField
in this output to FirstField
without touching base class code (because I will use it too and the names must be original). How can I accomplish this?
谢谢。
推荐答案
试试这个:
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;
}
您的序列化程序初始化更容易:
And your serializer init is a lot easier:
var xmls = new System.Xml.Serialization.XmlSerializer(typeof(Two), Two.XmlOverrides);
这篇关于序列化中基类字段的自定义XML元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!