我正在尝试编写一些代码来反序列化XML文件。我环顾了一下,找到了一些让我采用以下方法的东西:
public static void Deserialize(string filePath)
{
RootObject ro = null;
string path = filePath;
XmlSerializer serializer = new XmlSerializer(typeof(RootObject));
StreamReader reader = new StreamReader(path);
ro = (RootObject) serializer.Deserialize(reader);
reader.Close();
}
但我得到的只是这个错误而且我不确定是什么导致它:
XML文档(2,2)中存在错误。
你在Deserialize()中看到的RootObject就是这个:我是XMl序列化/反序列化的新手,所以我不确定我是否已经100%正确定义它。
public class RootObject
{
public Services Services { get; set; }
}
public class Services
{
public Service TileMapService { get; set; }
}
public class Service
{
public string Title { get; set; }
public string href { get; set; }
}
我正在使用此方法首先创建XML文件,它似乎工作正常:
public static void WriteToXmlFile<T>(string filePath, T objectToWrite) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof (T));
writer = new StreamWriter(filePath);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
{
writer.Close();
}
}
}
它为我提供了一个如下所示的XML文件:
<RootObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Services>
<TileMapService>
<Title>Some title</Title>
<href>http://something</href>
</TileMapService>
</Services>
</RootObject>
答案 0 :(得分:2)
您的代码运行正常。 &#34; XML文档中存在错误(2,2)。&#34;可能是因为您的实际文件(不是WriteToXmlFile<T>
创建的文件)在开始时有空格,或者使用了错误的命名空间。查看.InnerException
以获取更多详细信息,或者(可能更简单)请发布实际 xml文件内容。它运行良好的例子(以及对两个关键方法的一些推荐调整):
static void Main()
{
RootObject obj = new RootObject
{
Services = new Services
{
TileMapService = new Service
{
Title = "abc",
href = "def"
}
}
};
WriteToXmlFile("foo.xml", obj);
var loaded = Deserialize<RootObject>("foo.xml");
var svc = loaded.Services.TileMapService;
System.Console.WriteLine(svc.Title); // abc
System.Console.WriteLine(svc.href); // def
}
public static void WriteToXmlFile<T>(string filePath, T objectToWrite)
{
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StreamWriter(filePath))
{
serializer.Serialize(writer, objectToWrite);
}
}
public static T Deserialize<T>(string filePath)
{
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StreamReader(filePath))
{
return (T)serializer.Deserialize(reader);
}
}