0

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

5
  • How big is the full XML file? Commented Oct 25, 2013 at 17:18
  • It's 13MB, it has some data for the app, unrelated to appsetting tag, but I have to have it there now. Commented Oct 25, 2013 at 17:18
  • 1
    Why you're not storing data and settings in separate files? Commented Oct 25, 2013 at 17:19
  • I did before. But it's not my choice. :) Commented Oct 25, 2013 at 17:21
  • Does anyone else think that a 12MB xml settings file is oversized for a process that has to live with less than 32MB process space? I would switch to a binary file, objects and serialze/ de-serialize. Commented Oct 26, 2013 at 3:27

2 Answers 2

1

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")
      };
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I just had to set IgnoreWhitespace to true in addition.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.