【发布时间】:2015-02-25 13:27:42
【问题描述】:
我有一个非常大的 xml 文件(假设它有大约 300000 个元素)。在我的应用程序部分,我只需要知道根元素的名称是否为 ApplicationLog 以及根元素中是否有一个名为 LogId 的属性。
读取我使用的 XML:
XDocument document;
using (StreamReader streamReader = new StreamReader(filePath, true))
{
document = XDocument.Load(streamReader);
}
并获取我需要的信息:
try
{
if (document.Root != null)
{
if (string.Equals(document.Root.Name.LocalName, "ApplicationLog", StringComparison.InvariantCultureIgnoreCase) &&
document.Root.HasAttributes && (from o in document.Root.Attributes() where string.Equals(o.Name.LocalName, "LogId", StringComparison.InvariantCultureIgnoreCase) select o).Any())
{
isRelevantFile = true;
}
}
}
catch (Exception e)
{
}
这很好用。
问题是XDocument.Load 需要大约 15 秒来加载大约 20MB 的 XML 文件。
我也尝试使用XmlDocument,但我也遇到了同样的问题。
我对解决方案的第一个想法是将文件作为文本读取并解析搜索元素/属性的第一行。但这对我来说似乎不是那么专业。
有没有人知道更好的方法来实现这一点?
【问题讨论】:
-
如果您有一个简单且有效的解决方案,它怎么能不专业?
标签: c# xml linq-to-xml xmldocument