反序列化 XML 错误 [英] Deserialization XMl Error
本文介绍了反序列化 XML 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
列表的序列化不会遇到问题.创建 XML 文件:
The serialization of a list doesn't face problems. Creation of the XML File:
XmlDocument toolConfig = new XmlDocument();
XmlNode myRoot;
myRoot = toolConfig.CreateElement("Tool");
toolConfig.AppendChild(myRoot);
toolConfig.Save(@userConfigurePath + "\\config.xml");
序列化后的xml文件如下所示:
After the serialization the xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Tools xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Tool>
<Name>test</Name>
<Path>C:\Program Files\FreePDF_XP\freepdf.exe</Path>
</Tool>
<Tool>
<Name>test2</Name>
<Path>C:\Program Files\FreePDF_XP\fpconfig.exe</Path>
</Tool>
<Tool>
<Name>test3</Name>
<Path>C:\Program Files\FreePDF_XP\redrun.exe</Path>
</Tool>
</Tools>
反序列化代码:
private void ToolHandling_Loaded(object sender, RoutedEventArgs e)
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Tool>));
using (var reader = new StreamReader(@Start.userConfigurePath +
"\\config.xml"))
{
toolList = (List<Tool>)deserializer.Deserialize(reader);
reader.Close();
}
我收到 XML 文档错误 2,2:System.InvalidOperationException:XML 文档中有错误 (2, 2).因此,我对文档使用了验证工具,但没有出现错误.错误的根源在哪里?
I get the XML Document Error 2,2 : System.InvalidOperationException: There is an error in XML document (2, 2). Therefore I used a validation tool for the document and I got no error . Where is the source of the error?
编写xml的完整代码:
Full code to compose the xml:
private List<Tool> toolList = new List<Tool>();
private void ToolHandling_Closed(object sender, EventArgs e)
{
XmlSerializer serializer = new XmlSerializer(toolList.GetType(), new
XmlRootAttribute("Tools"));
using (var writer = new StreamWriter(@Start.userConfigurePath +
"\\config.xml"))
{
serializer.Serialize(writer, toolList);
writer.Close();
}
}
推荐答案
反序列化时忘记指定根属性:
You forgot to specify root attribute while de-serializing:
XmlSerializer deserializer = new XmlSerializer(typeof(List<Tool>) , new XmlRootAttribute("Tools"));
这篇关于反序列化 XML 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文