【问题标题】:Getting Data from Huge xml files without Loading into memory. c#从巨大的 xml 文件中获取数据而不加载到内存中。 C#
【发布时间】:2014-11-20 11:18:03
【问题描述】:

我有一个具有以下模式的 xml。

<root>
 <Main1>
   .
   .
   .
 <Main1/>
 <Main2>
   <Main2ChildNode Id="1">Very Very Huge Base 64 String<Main2ChildNode>
   <Main2ChildNode Id="2">Very Very Huge Base 64 String<Main2ChildNode>
    .
    .
    .
   <Main2ChildNode Id="n">Very Very Huge Base 64 String<Main2ChildNode>
 <Main2/>
</root>

我没有将 xml 加载到内存中,而是尝试基于 Id 属性访问每个 Main2ChildNode 的内部文本。我需要收集 Main2 部分下的全部数据,并以这种方式进一步处理。我正在尝试的以下代码逐行遍历整个 xml。

有没有更好的方法来识别特定 Main2ChildNode 的内部文本并具有良好的性能。

 private String GetImageData(String Main2ChildNodeId,String XmlFilePath)
    {
         string data=null;
         using (XmlReader reader = XmlReader.Create(XmlFilePath))
         {
             reader.MoveToContent();
             while (reader.Read() && data == null)
             {
                 switch (reader.NodeType)
                 {
                     case XmlNodeType.Element:
                         if (reader.Name == "Main2ChildNode")
                         {
                             XElement el = XElement.ReadFrom(reader) as XElement;
                             if ((String)el.Attribute("Id") == Main2ChildNodeId)
                             {
                                 data= el.Value;
                             }
                         }
                         break;
                 }
             }
         }
         return data
    }

请提出更好的解决方案。

【问题讨论】:

    标签: c# memory-management xml-parsing


    【解决方案1】:

    尝试使用基于事件的 SAX,即在解析时触发事件,而不是一次读取整个文档。它有助于在分区中加载 XML。

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 2017-06-16
      • 2020-06-05
      相关资源
      最近更新 更多