【发布时间】:2017-12-21 15:52:49
【问题描述】:
我正在尝试遍历目录以搜索所有 xml 文件。我通过执行Directory.EnumerateFiles 并找到每个 .xml 类型来完成此任务。现在的问题是,有一些随机的 xml 文件是空的,其中没有写入任何信息。我想检查所有没有任何信息的文件。
代码
foreach (string file in Directory.EnumerateFiles("/xmlFiles", "*.xml", SearchOption.AllDirectories))
{
//Find the XML File
XDocument doc = XDocument.Load(file);
//Check if the XDocument doc has no root element
if (doc == null)
{
Console.WriteLine(File + " has NO root element");
}
else
{
Console.WriteLine(File + " has a root element");
}
}
我尝试在解析 xml 文件后执行 if else 语句将文件与 null 进行比较,但在加载文件时出现错误,然后才能进行比较。
错误: System.Xml.XmlException: '缺少根元素。'
【问题讨论】:
标签: c# .net xml exception-handling