Click here to Skip to main content
13,006,195 members (78,393 online)
Rate this:
Please Sign up or sign in to vote.
See more:
How can I deserialize following XML file using C# classes. But I don't want to use XMLReader or same thing. I need to know how it can be done by using C# classes and its properties

    <Visibilities AppName="Test2">
      <Visibility DisplayName="Full Name" ListOrder="2">
          <FirstName PropertyName="FullName.FirstName" DisplayName="First Name"></FirstName>
          <MiddleName PropertyName="FullName.MiddleName" DisplayName="Middle Name"></MiddleName>
          <LastName PropertyName="FullName.LastName" DisplayName="Last Name"></LastName>

I want to use following function

 public static T LoadXml<T>(string fileName) where T : new()
            StreamReader reader = null;
                // Deserialize
                XmlSerializer ser = new XmlSerializer(typeof(T));
                reader = new StreamReader(fileName);
                T t = (T)ser.Deserialize(reader);
                if (t == null) throw new NullReferenceException("Invalid xml format");
                return t;
            catch (Exception ex)
                //TODO: Error
                if (reader != null) reader.Close();
            return new T();

Thanks in Advance.
Posted 11-May-13 5:04am
Updated 11-May-13 5:17am
Dave Kreskowiak 11-May-13 12:33pm
Why would you want to re-invent "the wheel"??
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

What you really need is Data Contract:[^].

Please see my past answers advocating this approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^].

This is much better then the solution referenced in Solution 1. The difference is performance. Data Contract serializer does the reflection only once per type. It creates a serialization assembly on the fly, using System.Reflection.Emit. If you wanted to develop similar solution by yourself, you would face with the need to know CIL very well, and Emit code is quite difficult to debug.

Rate this: bad
Please Sign up or sign in to vote.

Solution 1


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170628.1 | Last Updated 16 May 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100