【发布时间】:2017-06-07 20:50:02
【问题描述】:
为了尽量减少阅读错误日志所花费的时间,我创建了以下小插件,它将解析 Elmah 错误日志中包含的相关信息,并最终生成 Excel 电子表格。目前我正在使用 WriteLine 进行测试。我面临的问题是,在第二个 foreach 循环中,我在每个 node.attribute 项中都看到了一个空引用异常。此代码的预期结果是从每个 XML 文档的 <error> 标记中生成一个“属性”值列表。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
namespace ExcelSortingAutomation
{
public class Program
{
public static void Main(string[] args)
{
DirectoryInfo Exceptions = new DirectoryInfo("C:\\ErrorsMay2017");
FileInfo[] ExceptionFiles = Exceptions.GetFiles("*.xml");
foreach (var exception in ExceptionFiles)
{
string xml = "<error></error>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode node in doc.SelectNodes("//error"))
{
string errorId = node.Attributes["errorId"].Value;
string type = node.Attributes["type"].Value;
string message = node.Attributes["message"].Value;
string time = node.Attributes["time"].Value;
Console.WriteLine("{0} - {1} - {2} = {3}", errorId, type, message, time);
}
}
}
}
}
我的问题是,为什么此时应该提取和解析的日志没有接收到属性值?
编辑 1:仔细检查后,返回的 XmlNode 节点值没有“HasAttributes”
【问题讨论】:
-
行
string xml = "<error></error>";应该替换为string xml = File.ReadAllText(exception.FullName)); -
@JamesCurran 效果很好。我可以请您将其设置为答案以便我接受吗?
-
我期待您说“该行仅用于示例。我在真实代码中读取了文件”。然后我要说“然后用文件中的一些实际 sn-p 替换
”
标签: c# xml linq xml-parsing