简体   繁体   中英

Get XML node from large XML file with XmlReader?

How can I efficiently get XML node from large XML file?

Currently I have this code to load XML file and getting NodeList. This worked fine when that file was small (containing only that node). However, when I merged it with another XML file, Loading that new entire file cases my Windows Mobile device to crash (out of memory)

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(configFile);
XmlNodeList nodeList = xmlDocument.GetElementsByTagName("appsettings");

My XML is looks like this (I want to get appsettings which controls visibility of buttons in my app):

<site>
<settings>
<appsettings>
<add key="0" type="Home" value="True"/>
<add key="1" type="About" value="False"/>
<add key="2" type="Contact" value="True"/>
</appsettings>
...........
</settings>
</site>

How can I search for this node with XmlReader and load it into nodeList ? I have tried to use

You should use an XmlReader . Something like:

using (var reader = XmlReader.Create("file://path/to/file"))
{
  reader.ReadToDescendant("appsettings");
  while (reader.Read() && reader.Name == "add")
  {
    yield return new
      {
        Key = reader.GetAttribute("key"),
        Type = reader.GetAttribute("type"),
        Value = reader.GetAttribute("value")
      };
  }
}

Have you tried LINQ to XML ? (The old model is soooo 40s :P)

maybe something like this:

var xmlDoc = XDocument.Load(@"E:\Xml.xml");
var query = xmlDoc.Root.Element("settings").Descendants().First();

We know that the "appsettings" node always reside on a specific level. So we take the root and query for the settings node. Then we take the decsendants of that node and take the first of it. Which in the current case is "appsettings".

I know there is a LINQ way to make this even better, but this is what I could think of out of my head with no visual studio or LINQPad.

Hope this helps.

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