【问题标题】:Read only root-element from XML只读 XML 中的根元素
【发布时间】: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


【解决方案1】:

XmlReader API 用于

using (XmlReader xr = XmlReader.Create(filePath))
{
  xr.MoveToContent();
  if (xr.LocalName == "ApplicationLog" ...)

}

【讨论】:

    【解决方案2】:

    您可以尝试here 提供的解决方案或使用/开发SAX 阅读器,例如this one。您可以在 SAX here 上找到更多信息。

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多