C# 反序列化异常处理
如果我阅读此xml:C# 反序列化异常处理,c#,xml,exception,deserialization,C#,Xml,Exception,Deserialization,如果我阅读此xml: <?xml version="1.0"?> <Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <FontPath>sciezka</FontPath> <CodingCP852v2>44</CodingCP8
<?xml version="1.0"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FontPath>sciezka</FontPath>
<CodingCP852v2>44</CodingCP852v2>
<LedText>Napismoj</LedText>
</Settings>
现在,我想从引起异常的字段wch的异常对象名称中读取(在本例中,我应该得到“编码”)。怎么做
[Serializable]
public class Settings
{
public string FontPath
{
get;
set;
}
public bool Coding
{
get;
set;
}
}
try
{
using (FileStream s = File.OpenRead(fileName))
{
XmlSerializer xs = new XmlSerializer(typeof(Settings));
return (Settings)xs.Deserialize(s);
}
}
catch (Exception ex)
{
return new Settings();
}
XmlSerializer将始终引发和InvalidOperationException
。本例中的内部异常是System.Xml.XmlException
此异常的文档将向您显示可能可用的属性。它们都不是错误节点的名称
获取名称的唯一方法似乎是使用
XmlReader
手动解析文档,然后自己检查类型。如果省略模式,这将为您提供对类型映射和验证的细粒度控制 我必须问一下为什么首先要编码布尔值?您是否考虑过只显示异常文本?我突然想到,您希望允许这样的错误的唯一原因是因为您有用户可编辑的xml输入。您也可以让他们暴露在错误中,因为他们熟悉xml。输入行号和列号,它们就拥有识别错误值所需的所有信息。这可能是一个错误,XML文件中除了元素的错误值之外,还有许多其他可能的错误。试图从损坏的文件中生成有用的信息是危险的,您的“有用信息”也很可能会被损坏。发送用户进行一场白费力气的追逐。您已经得到了一个很好的内部异常,它告诉用户在文件中查找损坏的确切位置,但没有帮助。
[Serializable]
public class Settings
{
public string FontPath
{
get;
set;
}
public bool Coding
{
get;
set;
}
}
try
{
using (FileStream s = File.OpenRead(fileName))
{
XmlSerializer xs = new XmlSerializer(typeof(Settings));
return (Settings)xs.Deserialize(s);
}
}
catch (Exception ex)
{
return new Settings();
}