Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Fastest way to read XML

Fastest way to read XML

Scheduled Pinned Locked Moved C#
xmlquestion
7 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    tommazzo
    wrote on last edited by
    #1

    Hi! If I have a class with a certain number of properties, which I want to save to an XML file, where it is critical that the data can be read back into the variables as fast as possible. My idea is to create an XmlTextReader and then read the values as follows: while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.LocalName) { case "Prop1": m_Prop1 = reader.ReadString(); break; case "Prop2": m_Prop2 = reader.ReadString(); break; case "Prop3": m_Prop3 = reader.ReadString(); break; case "Prop4": m_Prop4 = reader.ReadString(); break; case "Prop5": m_Prop5 = reader.ReadString(); break; case "Prop6": m_Prop6 = reader.ReadString(); break; default: break; } } } I just want to make sure that I am in fact using the fastes possible way. So can anyone think of anything faster? Thanks already in advance!

    T 1 Reply Last reply
    0
    • T tommazzo

      Hi! If I have a class with a certain number of properties, which I want to save to an XML file, where it is critical that the data can be read back into the variables as fast as possible. My idea is to create an XmlTextReader and then read the values as follows: while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.LocalName) { case "Prop1": m_Prop1 = reader.ReadString(); break; case "Prop2": m_Prop2 = reader.ReadString(); break; case "Prop3": m_Prop3 = reader.ReadString(); break; case "Prop4": m_Prop4 = reader.ReadString(); break; case "Prop5": m_Prop5 = reader.ReadString(); break; case "Prop6": m_Prop6 = reader.ReadString(); break; default: break; } } } I just want to make sure that I am in fact using the fastes possible way. So can anyone think of anything faster? Thanks already in advance!

      T Offline
      T Offline
      turbochimp
      wrote on last edited by
      #2

      Why not just use XML serialization to write the instance to XML (assuming you're able to serialize everything you need to get using XML serialization)? Example (assuming you wanted to save the XML file to disk):// Saves the class instance to disk. string path = @"C:\MyClassInstance.xml"; XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); using(StreamWriter writer = new StreamWriter(path, false)) { serializer.Serialize(writer, myInstance); // assumes myInstance is an object of the type MyClass... writer.Close(); } // Loads the class instance XML file from disk and deserializes it MyClass instance = null; string path = @"C:\MyClassInstance.xml"; if(File.Exists(path)) { XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); using(StreamReader reader = new StreamReader(path)) { info = serializer.Deserialize(reader) as MyClass; reader.Close(); } }
      That should be pretty fast...

      The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

      T 1 Reply Last reply
      0
      • T turbochimp

        Why not just use XML serialization to write the instance to XML (assuming you're able to serialize everything you need to get using XML serialization)? Example (assuming you wanted to save the XML file to disk):// Saves the class instance to disk. string path = @"C:\MyClassInstance.xml"; XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); using(StreamWriter writer = new StreamWriter(path, false)) { serializer.Serialize(writer, myInstance); // assumes myInstance is an object of the type MyClass... writer.Close(); } // Loads the class instance XML file from disk and deserializes it MyClass instance = null; string path = @"C:\MyClassInstance.xml"; if(File.Exists(path)) { XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); using(StreamReader reader = new StreamReader(path)) { info = serializer.Deserialize(reader) as MyClass; reader.Close(); } }
        That should be pretty fast...

        The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

        T Offline
        T Offline
        tommazzo
        wrote on last edited by
        #3

        Normally that would be an idea, however I don't have to serialize all of my class' properties. Those that need not be serialized are actually created from the serialized ones. So XmlSerializer is unfortunately out of the question for me.

        T 1 Reply Last reply
        0
        • T tommazzo

          Normally that would be an idea, however I don't have to serialize all of my class' properties. Those that need not be serialized are actually created from the serialized ones. So XmlSerializer is unfortunately out of the question for me.

          T Offline
          T Offline
          turbochimp
          wrote on last edited by
          #4

          Why do you say that using XML serialization would be out of the question just because you have some properties you might not want to serialize? If you have properties you want to hide during serialization, then just mark them with the XmlIgnoreAttribute. There are obvious advantages to using XML serialization besides the fact that it's probably faster than rolling your own solution. It's vastly more tolerant of changes to structure of the class being serialized, and almost impossible to accidentally create malformed XML. Here's an example - enjoy...:using System; using System.IO; using System.Xml.Serialization; namespace XmlSerializationExample { class Example { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { MyClass mc = new MyClass(); mc.Property1 = "a"; mc.Property2 = "b"; mc.Property3 = "c"; mc.PickANumber = 1234; mc.IgnoreThisProperty = "Blahblahblahblah."; mc.Save(@"c:\serialized_myclass.xml"); MyClass mc2 = MyClass.Load(@"c:\serialized_myclass.xml"); Console.WriteLine("Deserialized Property1: {0}", mc2.Property1); Console.WriteLine("Deserialized Property2: {0}", mc2.Property2); Console.WriteLine("Deserialized Property3: {0}", mc2.Property3); Console.WriteLine("Deserialized PickANumber: {0}", mc2.PickANumber); Console.WriteLine("Deserialized ComboProperty: {0}", mc2.ComboProperty); Console.WriteLine("Deserialized IgnoreThisProperty: {0}", mc2.IgnoreThisProperty); Console.ReadLine(); } } public class MyClass { #region Fields // These fields will not be directly serialized - they are private private string _field1; private string _field2; private string _field3; private string _ignoredField; // This field will be directly serialized, since it is public // (don't do this - bad practice) public int PickANumber; #endregion Fields #region Constructor public MyClass(){} #endregion Constructor #region Properties /// /// Property1 will be serialized because it is a public property with 'get' and 'set' accessors. /// public string Property1 { get{return _field1;} set{_field1 = value;} } /// /// Property2 will be serialized because it is a public property with 'get' and 'set' accessors. /// public string Property2 { get{return _field2;}

          T 1 Reply Last reply
          0
          • T turbochimp

            Why do you say that using XML serialization would be out of the question just because you have some properties you might not want to serialize? If you have properties you want to hide during serialization, then just mark them with the XmlIgnoreAttribute. There are obvious advantages to using XML serialization besides the fact that it's probably faster than rolling your own solution. It's vastly more tolerant of changes to structure of the class being serialized, and almost impossible to accidentally create malformed XML. Here's an example - enjoy...:using System; using System.IO; using System.Xml.Serialization; namespace XmlSerializationExample { class Example { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { MyClass mc = new MyClass(); mc.Property1 = "a"; mc.Property2 = "b"; mc.Property3 = "c"; mc.PickANumber = 1234; mc.IgnoreThisProperty = "Blahblahblahblah."; mc.Save(@"c:\serialized_myclass.xml"); MyClass mc2 = MyClass.Load(@"c:\serialized_myclass.xml"); Console.WriteLine("Deserialized Property1: {0}", mc2.Property1); Console.WriteLine("Deserialized Property2: {0}", mc2.Property2); Console.WriteLine("Deserialized Property3: {0}", mc2.Property3); Console.WriteLine("Deserialized PickANumber: {0}", mc2.PickANumber); Console.WriteLine("Deserialized ComboProperty: {0}", mc2.ComboProperty); Console.WriteLine("Deserialized IgnoreThisProperty: {0}", mc2.IgnoreThisProperty); Console.ReadLine(); } } public class MyClass { #region Fields // These fields will not be directly serialized - they are private private string _field1; private string _field2; private string _field3; private string _ignoredField; // This field will be directly serialized, since it is public // (don't do this - bad practice) public int PickANumber; #endregion Fields #region Constructor public MyClass(){} #endregion Constructor #region Properties /// /// Property1 will be serialized because it is a public property with 'get' and 'set' accessors. /// public string Property1 { get{return _field1;} set{_field1 = value;} } /// /// Property2 will be serialized because it is a public property with 'get' and 'set' accessors. /// public string Property2 { get{return _field2;}

            T Offline
            T Offline
            tommazzo
            wrote on last edited by
            #5

            Thanks, I didn't think of the XmlIgnore attribute. Just out of interest, if I added a property, would XmlSerializer still be able to read files that did not have that property yet?

            T 1 Reply Last reply
            0
            • T tommazzo

              Thanks, I didn't think of the XmlIgnore attribute. Just out of interest, if I added a property, would XmlSerializer still be able to read files that did not have that property yet?

              T Offline
              T Offline
              turbochimp
              wrote on last edited by
              #6

              The deserialization should ignore missing property values in the XML, although you might get into some trouble if you changed the type of an existing property to something that can't be coerced from the previous type (e.g. changing a string to a decimal or something), then tried to load previously serialized versions of the type. Good luck.

              The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

              T 1 Reply Last reply
              0
              • T turbochimp

                The deserialization should ignore missing property values in the XML, although you might get into some trouble if you changed the type of an existing property to something that can't be coerced from the previous type (e.g. changing a string to a decimal or something), then tried to load previously serialized versions of the type. Good luck.

                The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

                T Offline
                T Offline
                tommazzo
                wrote on last edited by
                #7

                I don't think I'll ever have to change the type of a property, my only concern was newly added properties. Thanks for clearing this up for me!

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups