XDocument.Load(XmlReader)
方法被调用时可能会引发哪些异常? 当文档未提供关键信息时,遵循最佳实践(例如避免使用通用的try catch块)可能会很困难。
感谢您的帮助。
XDocument.Load(XmlReader)
方法被调用时可能会引发哪些异常? 当文档未提供关键信息时,遵循最佳实践(例如避免使用通用的try catch块)可能会很困难。
感谢您的帮助。
根据MSDN文档,LINQ to XML的加载功能是基于XmlReader构建的。因此,您可能会捕获到由XmlReader引发的任何异常。创建重载方法和读取和解析文档的XmlReader方法。
http://msdn.microsoft.com/en-us/library/756wd7zs.aspx ArgumentNullException和SecurityException
编辑:MSDN并不总是准确的。因此,我使用反编译器分析了Load方法代码,并得到了如下结果:
public static XDocument Load(XmlReader reader)
{
return Load(reader, LoadOptions.None);
}
方法 Load 在调用以下方法:
public static XDocument Load(XmlReader reader, LoadOptions options)
{
if (reader == null)
{
throw new ArgumentNullException("reader"); //ArgumentNullException
}
if (reader.ReadState == ReadState.Initial)
{
reader.Read();// Could throw XmlException according to MSDN
}
XDocument document = new XDocument();
if ((options & LoadOptions.SetBaseUri) != LoadOptions.None)
{
string baseURI = reader.BaseURI;
if ((baseURI != null) && (baseURI.Length != 0))
{
document.SetBaseUri(baseURI);
}
}
if ((options & LoadOptions.SetLineInfo) != LoadOptions.None)
{
IXmlLineInfo info = reader as IXmlLineInfo;
if ((info != null) && info.HasLineInfo())
{
document.SetLineInfo(info.LineNumber, info.LinePosition);
}
}
if (reader.NodeType == XmlNodeType.XmlDeclaration)
{
document.Declaration = new XDeclaration(reader);
}
document.ReadContentFrom(reader, options); // InvalidOperationException
if (!reader.EOF)
{
throw new InvalidOperationException(Res.GetString("InvalidOperation_ExpectedEndOfFile")); // InvalidOperationException
}
if (document.Root == null)
{
throw new InvalidOperationException(Res.GetString("InvalidOperation_MissingRoot")); // InvalidOperationException
}
return document;
}
有可能会出现异常的行已被注释掉。
我们可能会遇到以下异常:ArgumentNullException,XmlException和InvalidOperationException。MSDN说可能会出现SecurityException,但在创建XmlReader时也可能出现此类异常。
XmlReader.Create(Stream)
可能会引发两种类型的异常:[src]
XmlReader reader; // Do whatever you want
try
{
XDocument.Load(reader);
}
catch (ArgumentNullException)
{
// The input value is null.
}
catch (SecurityException)
{
// The XmlReader does not have sufficient permissions
// to access the location of the XML data.
}
catch (FileNotFoundException)
{
// The underlying file of the path cannot be found
}
看起来在线文档没有说明抛出哪些异常...太糟糕了。使用FileInfo实例并调用它的Exists方法,以确保文件确实存在,这样您就不必捕获FileNotFoundException类型的异常,这样您就可以避免一些麻烦。
[编辑]
重新阅读您的帖子时,我忘记注意到您正在传递XML Reader。我的回答是基于传递代表文件的字符串(重载方法)。
鉴于此,我建议创建一个格式错误的XML测试文件并尝试加载它,以查看实际抛出的异常类型。然后处理这些情况。
XDocument.Load("...")
来加载一个.html页面时,我遇到了以下异常:System.Xml.XmlException: ''src' is an unexpected token. The expected token is '='. Line 47, position 32.'
因此,根据您要解析的内容以及是否需要更宽松的解析方式,也许其他库更适合。我选择了IronWebScraper,它对我正在处理的HTML效果更好。