Solved

C# XML  The most efficient way of loading a XML file

Posted on 2004-10-28
639 Views
Last Modified: 2011-10-03
I have my XML file:

<ServerConnection>Network Library=My_SQLDB_STRING</ServerConnection>
<ServerConnectionTimeout>Connect Timeout=2;</ServerConnectionTimeout>
<ItemDB>
    <Server Title="t1">test1</Server>
    <Server Title="t2">test2</Server>
    <Server Title="t3">test3</Server>
    <Server Title="t4">test4</Server>
    <Server Title="t5">test5</Server>
</ItemDB>

There are x amounts of <Server> elements within ItemDB.

I want to capture the ServerConnection and ServerConnectionTimeout in 2 seperate Strings,

Then create an arraylist of all <server>'s that are under ItemDB.

I'm tossing around XML DOM or the XML reader, but I want it efficient so it doesn't slow our live servers down. This is small app that runs behind the scenes to query tables to see if email reminders must be sent out, and queries the DB's every minute to see if there's a reminder at that time.

Thanks!
0
Question by:icompass
    11 Comments
     
    LVL 5

    Expert Comment

    by:Kelmen
    XmlReader should be your pick.

    As stated in the MSDN:

    Represents a reader that provides fast, non-cached, forward-only access to XML data.

    I would use the DOM if the xml and the data volume won't penalize the perf. And if the loaded xml will be reuse, DOM will give better throughput.

    DOM - volume not huge, reuse

    * Reuse = it will be used for process few/more times in one run

    XmlReader - huge volume, 1 time process.
    0
     
    LVL 13

    Expert Comment

    by:dungla
    I think maybe you should try XMLTextReader, simply like that

    public static void ReadXML(out string ServerConnection, out string ConnectionTimeOut, out ArrayList Servers)
                {
                      ServerConnection = "";
                      ConnectionTimeOut = "";
                      Servers = new ArrayList();

                      XmlTextReader reader = new XmlTextReader(@"D:\test.xml");
                      while(reader.Read())
                      {
                            reader.MoveToElement();
                            if (reader.Name == "ServerConnection")
                            {
                                  ServerConnection = reader.ReadInnerXml();
                            }
                            if (reader.Name == "ServerConnectionTimeOut")
                            {
                                  ConnectionTimeOut = reader.ReadInnerXml();
                            }
                            if (reader.Name == "Server")
                            {
                                  Servers.Add(reader.ReadInnerXml());
                            }
                      }
    0
     
    LVL 7

    Expert Comment

    by:NipNFriar_Tuck
    Why not create a data class to handle the information and serialiaze/deserialize it to/from xml?
    0
     
    LVL 15

    Expert Comment

    by:SRigney
    As long as we're going to throw all options out here.  Why don't you use ADO.Net dataset to read it with ReadXML.  Then the array, will already be set up in a table and you can loop through it easily.
    0
     

    Author Comment

    by:icompass
    This is for reading only, I don't need to write anything.

    I tried dungla's way, but that gave me a lot of errors after it parsed the ServerConnection.
    I can get the ServerConnection and ConnectionTimeOut, but I'm not 100% fluent in C# with XML yet and I don't really know how to loop through the

    <ItemDB>
        <Server Title="t1">test1</Server>
        <Server Title="t2">test2</Server>
        <Server Title="t3">test3</Server>
        <Server Title="t4">test4</Server>
        <Server Title="t5">test5</Server>
    </ItemDB>

    part to get everything.
    0
     
    LVL 7

    Accepted Solution

    by:
    there are a couple of ways that you can do this...

    one you can loop through nodes... easy to do but slow...

    foreach ( XmlNode n in XmlDoc.ChildNodes ) {
       switch ( XmlNode.Name ) {
          case "ServerConnection":
              // do stuff
              string sConn = n.Value.ToString();
              break;
          case "ConnectionTimeOut":
              // do stuff
              string sTimeOut = n.Value.ToString();
              break;
          case "ItemDB":
              // do stuff
              foreach ( XmlNode cn in n.ChildNodes ) {
                   // Do more stuff
                   string sTitle = cn.Value.ToString();
              }
              break;
       }
    }

    The other you can use XPath... here is a site to explain that...

    http://www.zvon.org/xxl/XPathTutorial/Output/example1.html

    Hope this helps...
    0
     
    LVL 14

    Expert Comment

    by:AvonWyss
    DOM is slow, Datasets are slower. If you are looking for performance, this is not an option.

    XmlTextReader as shown by Dungla would be my pick also. Note that you can also read the inner data of the Server node easily using the MoveToAttribute(name) method.

    Note that the XML file you posted is invalid, it lacks a root XML node.
    0
     
    LVL 13

    Expert Comment

    by:dungla
    icompass,

    Can you show me the errors message? I have tested the code, the function ReadXML() receive 3 params as out param which met your expectation, i think so.

    Here is my code
    ==== MyClass.cs ====
    using System;
    using System.Xml;
    using System.Collections;
    class MyClass
    {
     static void Main(string[] args)
     {
       string ServerConnection;
       string ConnectionTimeOut;
       ArrayList Servers;
      ReadXML(out ServerConnection, out ConnectionTimeOut, out Servers);
      Console.WriteLine("ServerConnection = {0}", ServerConnection);
      Console.WriteLine("ConnectionTimeOut = {0}", ConnectionTimeOut);
      for (int j = 0; j < Servers.Count; j++)
      {
         Console.WriteLine("Server {0} = {1}", j.ToString(), Servers[j].ToString());
      }
      Console.ReadLine();
     }
     public static void ReadXML(out string ServerConnection, out string ConnectionTimeOut, out ArrayList Servers)
    {... code above}
    }
    ======== end of MyClass ====

    I tested and have no errors while trying to read through the XML file and get all the node. Just try it again.

    If you till receive errors, post here, it's might helpful for me to help you

    Hope this help!

    .:: LDLP ::.
    0
     
    LVL 13

    Expert Comment

    by:dungla
    icompass,

    In my code, when met the node name "Server" as in your XML file, get the value of the node and put into an array list. If you want to get the attribute of "Server" node, use AttributeCount, MoveToAttribute(string name), GetAttribute(string name) method to get all the attribute.

    Hope this help
    .:: LDLP ::.
    0
     
    LVL 14

    Expert Comment

    by:AvonWyss
    You were asking for the most EFFICIENT way to load the file. The question you picked may be the most CONVENIENT, but it's certainly not the most EFFICIENT. This is not very fair for the experts like kelmen or dungla which actually gave you the correct answer for your specific question.
    0
     

    Author Comment

    by:icompass
    AvonWyss,

    Yes I was asking for the most Efficient way, and I do not doubt that Kelmen and Dungla are excellent programmers. However I am restrained by time as well, and the solution I picked was the one using the XMLDocument. It was the only one I was able to get to work with my XML file.

    I've never played with XML before, and I'm a native VB coder switching to C#.
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    The Complete Ruby on Rails Developer Course

    Ruby on Rails is one of the most popular web development frameworks, and a useful tool used by both startups and more established companies to build strong graphic user interfaces, and responsive websites and apps.

    Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    Want to pick and choose which updates you receive? Feel free to check out this quick video on how to manage your email notifications.
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    884 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now