gpt4 book ai didi

c# - 反序列化 XMl 错误

转载 作者:太空宇宙 更新时间:2023-11-03 21:36:05 25 4
gpt4 key购买 nike

列表的序列化不会遇到问题。创建 XML 文件:

        XmlDocument toolConfig = new XmlDocument();
XmlNode myRoot;
myRoot = toolConfig.CreateElement("Tool");
toolConfig.AppendChild(myRoot);
toolConfig.Save(@userConfigurePath + "\\config.xml");

序列化后的 xml 文件如下所示:

     <?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) 中存在错误。因此,我对文档使用了验证工具,但没有出现任何错误。错误来源在哪里?

编辑:组成 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();
}
}

最佳答案

您在反序列化时忘记指定根属性:

XmlSerializer deserializer = new XmlSerializer(typeof(List<Tool>) , new XmlRootAttribute("Tools"));

关于c# - 反序列化 XMl 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21774351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com