假设我在同一个程序集中有两个不同的xml文件作为embedded-resource:
Hummer.xml
<?xml version="1.0" encoding="utf-8" ?>
<car company="GMC" brand="Hummer" />
HammerHead.xml
<?xml version="1.0" encoding="utf-8" ?>
<shark species="HammerHead" length="45" />
Car.cs 使用系统; 使用System.Collections.Generic; 使用System.Text; 使用System.Xml.Serialization;
namespace XmlDeserialization_Test
{
[XmlRoot("car"), XmlType("car")]
public class Car
{
[XmlAttribute("company")]
public string Company { get; set; }
[XmlAttribute("brand")]
public string Brand { get; set; }
}
}
Shark.cs 使用系统; 使用System.Collections.Generic; 使用System.Text; 使用System.Xml.Serialization;
namespace XmlDeserialization_Test
{
[XmlRoot("shark"), XmlType("shark")]
public class Shark
{
[XmlAttribute("species")]
public string Species { get; set; }
[XmlAttribute("length")]
public double Length { get; set; }
}
}
Program.cs的
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;
namespace XmlDeserialization_Test
{
class Program
{
static void Main(string[] args)
{
List<Car> carList = new List<Car>();
List<Shark> sharkList = new List<Shark>();
Assembly assembly = Assembly.LoadFrom("XmlDeserialization_Test.exe");
string[] manifestResourceNames = assembly.GetManifestResourceNames();
Array.Sort<string>(manifestResourceNames);
foreach (string mrn in manifestResourceNames)
{
Stream stream = assembly.GetManifestResourceStream(mrn);
XmlSerializer serializer = new XmlSerializer(typeof(Shark));
object obj = serializer.Deserialize(stream);
if (obj is Car)
{
carList.Add((Car)obj);
}
else if (obj is Shark)
{
sharkList.Add((Shark)obj);
}
}
}
}
}
HammerHead - Shark完美地反序列化。
但是,悍马 - 车不是。正在生成以下异常:
There is an error in XML document (2, 2).
"<car xmlns=''> was not expected."
如果Shark正在反序列化,为什么Car不是?如果汽车产生异常,为什么Shark不是?
我无能为力!!!
答案 0 :(得分:3)
你正在尝试用“鲨鱼”反序列化“汽车”对象。如果更改为创建Car类型的反序列化器,则会产生相反的结果:
XmlSerializer serializer = new XmlSerializer(typeof( Car ));
我不知道你是如何序列化的,但这应该会给你一个想法。