仅捕获 XmlException 中的字符编码问题
我正在使用 System.Xml 来解析 xml 文档。有时 xml 文档包含无法编码的字符,然后抛出 XmlException
。在这些情况下,我想使用强制编码重试解析文档,如下所示:
try {
var doc = new XmlDocument();
doc.Load()
} catch (XmlException xe) {
// Retry here with another encoding..
}
除了所有类型的 xml 问题(甚至不是由字符编码问题引起的问题)抛出 XmlException 之外,这种方法效果相当好。在这些情况下,我不想重试解析。那么有没有办法判断XmlException是由字符编码问题还是其他原因引起的呢?
I'm using System.Xml to parse xml documents. Sometimes the xml documents contain unencodable characters and then an XmlException
gets thrown. In those cases, I want to retry parsing the document with a forced encoding, like this:
try {
var doc = new XmlDocument();
doc.Load()
} catch (XmlException xe) {
// Retry here with another encoding..
}
This works fairly well except that XmlException gets thrown for all types of xml problems even those not caused by character encoding issues. In those cases I do not want to retry parsing. So is there a way to figure out whether the XmlException was caused by character encoding problems or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道异常到底是什么样的,但是通过检查 xe.Message 或 xe.InnerException 的内容,您肯定能够确定异常的类型?
I don't know exactly what the exception looks like, but surely by checking the contents of
xe.Message
orxe.InnerException
you would be able to determine the type of exception?我想答案是否定的,没有办法可靠地找出导致 XmlException 的原因。
I guess the answer is no, there is no way to robustly find out what caused the XmlException.