简体   繁体   中英

Getting Data from Huge xml files without Loading into memory. c#

I have an xml with the following pattern.

<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>

Instead of loading the xml into memory I am trying to access the inner text of each Main2ChildNode based on the Id Property. I need to collect entire data under Main2 section and process further in this way one by one. The below code which I am trying is iterating over the entire xml line by line.

Is there any better way to identify a specific Main2ChildNode 's inner text with good performance.

 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
    }

Please suggest a better solution.

Try Using SAX with is event based, ie event is triggered while parsing, rather than reading whole document at once. It helps to load XML in partition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM