假設我有一個相同的裝配兩種不同的XML文件作爲嵌入資源:爲什麼有兩種相同類型的xmls,一種不是反序列化,另一種是?
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 使用系統; using System.Collections.Generic; using System.Text; using 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 ; using System.Collections.Generic; using System.Text; using 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);
}
}
}
}
}
錘頭 - 鯊魚是完全反序列化。
但是,悍馬 - 車不是。正在生成以下異常:
There is an error in XML document (2, 2).
"<car xmlns=''> was not expected."
如果鯊魚被反序列化,爲什麼車是不是?如果汽車發生異常,爲什麼鯊魚不是?
我無能爲力!
從錯誤,它看起來像您的資源中的XML是不一樣的,你在這裏發佈。它抱怨不在您發佈的文檔中的內容。 – 2012-01-06 19:30:48
哪個xml悍馬或HammerHead? – anonymous 2012-01-06 19:31:34
悍馬。看起來它抱怨以下內容:。這不在您發佈的XML文檔中。 –
2012-01-06 19:32:15