C# 更改元素';xml c反序列化期间的s名称#
我有一个类似这样的类:C# 更改元素';xml c反序列化期间的s名称#,c#,xml,xml-deserialization,xmltype,typename,C#,Xml,Xml Deserialization,Xmltype,Typename,我有一个类似这样的类: [XmlType(TypeName = "rootType")] public class myClass { public Class1 class1; public Class2 class2; [XmlType(TypeName = "type1")] public class class1 { ... class1 definition ...} [XmlType(TypeName = "type2")]
[XmlType(TypeName = "rootType")]
public class myClass
{
public Class1 class1;
public Class2 class2;
[XmlType(TypeName = "type1")]
public class class1
{ ... class1 definition ...}
[XmlType(TypeName = "type2")]
public class class2
{ ... class1 definition ...}
}
void Serializer_UnknownElement(object sender, XmlElementEventArgs e)
{
myClass my = (myClass)e.ObjectBeingDeserialized;
if (e.Element.Name == "type1")
{
var ser = new XmlSerializer(typeof(myClass.Class1));
using (var sr = new StringReader(e.Element.OuterXml))
my.class1 = (myClass.Class1)ser.Deserialize(sr);
}
else if (e.Element.Name == "type2")
{
var ser = new XmlSerializer(typeof(myClass.Class2));
using (var sr = new StringReader(e.Element.OuterXml))
my.class2 = (myClass.Class2)ser.Deserialize(sr);
}
}
当我序列化它时,生成的xml将是
<rootType>
<class1>
... some stuff
<class1/>
<class2>
... some stuff
<class2/>
<rootType/>
... 一些东西
... 一些东西
然而,我这里的问题是,这些xmltype修饰刚刚添加到类中,这意味着在以前的版本(客户机使用)中,xml看起来像
<myClass>
<type1>
... some stuff
<type1/>
<type2>
... some stuff
<type2/>
<myClass/>
... 一些东西
... 一些东西
如果可能的话,有没有一种方法可以控制反序列化过程(或者解决这个问题的任何其他方法),并能够使用这些XmlType装饰将这个xml反序列化到myClass?您的问题完全解决了 首先,在创建序列化程序时,使用所需名称添加
XmlRootAttribute
参数
其次,将事件处理程序添加到序列化程序
var serializer = new XmlSerializer(typeof(myClass), new XmlRootAttribute("myClass"));
serializer.UnknownElement += Serializer_UnknownElement;
事件处理程序应如下所示:
[XmlType(TypeName = "rootType")]
public class myClass
{
public Class1 class1;
public Class2 class2;
[XmlType(TypeName = "type1")]
public class class1
{ ... class1 definition ...}
[XmlType(TypeName = "type2")]
public class class2
{ ... class1 definition ...}
}
void Serializer_UnknownElement(object sender, XmlElementEventArgs e)
{
myClass my = (myClass)e.ObjectBeingDeserialized;
if (e.Element.Name == "type1")
{
var ser = new XmlSerializer(typeof(myClass.Class1));
using (var sr = new StringReader(e.Element.OuterXml))
my.class1 = (myClass.Class1)ser.Deserialize(sr);
}
else if (e.Element.Name == "type2")
{
var ser = new XmlSerializer(typeof(myClass.Class2));
using (var sr = new StringReader(e.Element.OuterXml))
my.class2 = (myClass.Class2)ser.Deserialize(sr);
}
}
一如既往地使用:
myClass my;
using (var fs = new FileStream("test.xml", FileMode.Open))
my = (myClass)serializer.Deserialize(fs);
它应该可以工作。您只需转换旧的xml并将其输入到新的反序列化程序中即可。这可能是最简单的。@Rook,我只限于不转换旧的xml,但是xml怎么可能是不可转换的呢?你可以在第一次加载文件时在内存中完成,也可以将其转换为临时文件并加载。我将尝试一下!