CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 2002
    Posts
    1,798

    How to convert xml deserialized object to array

    Using .NET 4.6 on Win7(64bit). I have a relatively simple xml data set:

    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <Profile ID="1">
      <ClinicDr>Christian</ClinicDr>
      <ClinicDate>07/23/2016</ClinicDate>
      <PatNo>654321234</PatNo>
      <Surname>Fowler</Surname>
      <Forename>Martin</Forename>
      <Age>76</Age>
      <Sex>Male</Sex>
      <SBPToday>178</SBPToday>
      <SBPTarget>128</SBPTarget>
      <DBPToday>92</DBPToday>
      <DBPTarget>72</DBPTarget>
      <TCholToday>450</TCholToday>
      <TCholTarget>210</TCholTarget>
      <HDLToday>32</HDLToday>
      <HDLTarget>88</HDLTarget>
      <GlucoseToday>256</GlucoseToday>
      <GlucoseTarget>98</GlucoseTarget>
      <SmokToday>Yes</SmokToday>
      <SmokTarget>No</SmokTarget>
      <DiabToday>Yes</DiabToday>
      <DiabTarget>No</DiabTarget>
      <LVHToday>No</LVHToday>
      <LVHTarget>No</LVHTarget>
      <HTRxToday>Yes</HTRxToday>
      <HTRxTarget>Yes</HTRxTarget>
      <AfibToday>Yes</AfibToday>
      <AfibTarget>No</AfibTarget>
      <HxCHDToday>Yes</HxCHDToday>
      <HxCHDTarget>Yes</HxCHDTarget>
      <CHDRskToday>22</CHDRskToday>
      <CHDRskTarget>12</CHDRskTarget>
      <CHDRskGenPop>8</CHDRskGenPop>
      <StrkRskToday>8</StrkRskToday>
      <StrkRskTarget>4</StrkRskTarget>
      <StrkRskGenPop>4</StrkRskGenPop>
    </Profile>
    Code:
    namespace CvdRisk
    {
        /// <summary>
        /// Represents a single profile
        /// </summary>
        public class Profile
        {
            [XmlAttribute("ID")]
            public string Id { get; set; }
    
            [XmlElement("ClinicDr")]
            public string ClinicDr { get; set; }
    
            [XmlElement("ClinicDate")]
            public string ClinicDate { get; set; }
    
            [XmlElement("PatNo")]
            public string PatNo { get; set; }
    
            [XmlElement("Surname")]
            public string SurName { get; set; }
    
            [XmlElement("Forename")]
            public string ForeName { get; set; }
    
            [XmlElement("Age")]
            public string Age { get; set; }
    
            [XmlElement("Sex")]
            public string Sex { get; set; }
    
            [XmlElement("SBPToday")]
            public string SBPToday { get; set; }
    
            [XmlElement("SBPTarget")]
            public string SBPTarget { get; set; }
    
            [XmlElement("DBPToday")]
            public string DBPToday { get; set; }
    
            [XmlElement("DBPTarget")]
            public string DBPTarget { get; set; }
    
            [XmlElement("TCholToday")]
            public string TCholToday { get; set; }
    
            [XmlElement("TCholTarget")]
            public string TCholTarget { get; set; }
    
            [XmlElement("HDLToday")]
            public string HDLToday { get; set; }
    
            [XmlElement("HDLTarget")]
            public string HDLTarget { get; set; }
    
            [XmlElement("GlucoseToday")]
            public string GlucoseToday { get; set; }
    
            [XmlElement("GlucoseTarget")]
            public string GlucoseTarget { get; set; }
    
            [XmlElement("SmokToday")]
            public string SmokToday { get; set; }
    
            [XmlElement("SmokTarget")]
            public string SmokTarget { get; set; }
    
            [XmlElement("DiabToday")]
            public string DiabToday { get; set; }
    
            [XmlElement("DiabTarget")]
            public string DiabTarget { get; set; }
    
            [XmlElement("LVHToday")]
            public string LVHToday { get; set; }
    
            [XmlElement("LVHTarget")]
            public string LVHTarget { get; set; }
    
            [XmlElement("HTRxToday")]
            public string HTRxToday { get; set; }
    
            [XmlElement("HTRxTarget")]
            public string HTRxTarget { get; set; }
    
            [XmlElement("AfibToday")]
            public string AfibToday { get; set; }
    
            [XmlElement("AfibTarget")]
            public string AfibTarget { get; set; }
    
            [XmlElement("HxCHDToday")]
            public string HxCHDToday { get; set; }
    
            [XmlElement("HxCHDTarget")]
            public string HxCHDTarget { get; set; }
    
            [XmlElement("CHDRskToday")]
            public string CHDRskToday { get; set; }
    
            [XmlElement("CHDRskTarget")]
            public string CHDRskTarget { get; set; }
    
            [XmlElement("CHDRskGenPop")]
            public string CHDRskGenPop { get; set; }
    
            [XmlElement("StrkRskToday")]
            public string StrkRskToday { get; set; }
    
            [XmlElement("StrkRskTarget")]
            public string StrkRskTarget { get; set; }
    
            [XmlElement("StrkRskGenPop")]
            public string StrkRskGenPop { get; set; }
    
        }
    }
    I am able to deserialize this file. The class Profile is shown above and has been referred to in an earlier post:
    http://forums.codeguru.com/showthrea...ect&highlight=

    Code:
                XmlSerializer SerializerObj = new XmlSerializer(typeof(Profile));
    
                /// NB: When working to a defined schema, it is often necessary to remove the standard 
                /// namespace definitions that are added by the XmlSerializer. This is usually best 
                /// handled when calling the Serialize() method of the XmlSerializer instance. An optional 
                /// parameter for this method specifies the namespaces to be used, an XmlSerializerNamespaces 
                /// collection, and can contain blank values.
                /// https://blog.udemy.com/csharp-serialize-to-xml/
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
    
                // Create a new file stream to write the serialized object to a file
                TextWriter WriteFileStream = new StreamWriter(@"profile.xml");
                //SerializerObj.Serialize(WriteFileStream, profile);
                SerializerObj.Serialize(WriteFileStream, profile, ns);
    
                // Cleanup
                WriteFileStream.Close();
    
    
                //MySerializableClass myObject;
                Profile myObject;
                // Construct an instance of the XmlSerializer with the type
                // of object that is being deserialized.
                XmlSerializer mySerializer = 
                new XmlSerializer(typeof(Profile));
                // To read the file, create a FileStream.
                FileStream ReadFileStream = new FileStream(@"profile.xml", FileMode.Open);
                // Call the Deserialize method and cast to the object type.
                myObject = (Profile)mySerializer.Deserialize(ReadFileStream);
    
      
                Console.WriteLine("myObject.Id = " + myObject.Id.ToString());
                Console.WriteLine("myObject.ClinicDr = " + myObject.ClinicDr.ToString());
                Console.WriteLine("myObject.ClinicDate = " + myObject.ClinicDate.ToString());
                Console.WriteLine("myObject.PatNo = " + myObject.PatNo.ToString());
                Console.WriteLine("myObject.SurName = " + myObject.SurName.ToString());
                Console.WriteLine("myObject.ForeName = " + myObject.ForeName.ToString());
                Console.WriteLine("myObject.Age = " + myObject.Age.ToString());
                Console.WriteLine("myObject.Sex = " + myObject.Sex.ToString());
                // etc, etc, ...
    I would like to be able to convert the deserialized object (myObject) into an array of string, thus enabling a foreach loop to be used rather than laboriously selecting each element. How can I accomplish that?
    Last edited by Mike Pliam; July 24th, 2016 at 08:53 PM.
    mpliam

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How to convert xml deserialized object to array

    Override the ToString method of the Profile class. From within the Profile class, start typing the word override and you'll see the ToString method appear in intellisense.

    A couple of comments:
    1) In C#, local parameters are usually declared as camelCased rather than PascalCased.
    2) Use a using block to wrap the file stream objects (so they automatically close when they go out of scope). This is good practice for any objects that implement IDisposable.

  3. #3
    Join Date
    May 2002
    Posts
    1,798

    Re: How to convert xml deserialized object to array

    Thanks Arjay.

    Is this better?
    Code:
                using (TextWriter WriteFileStream = new StreamWriter(@"patients12.xml"))
                {
                    XmlSerializer listObj = new XmlSerializer(typeof(List<Profile>));
                    XmlSerializerNamespaces nms = new XmlSerializerNamespaces();
                    nms.Add("", "");
                    listObj.Serialize(WriteFileStream, list, nms);
                    WriteFileStream.Close();
                }
    As a C# newbie I'm unclear as how to check for memory leaks. Or does C# take care of such things?
    mpliam

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How to convert xml deserialized object to array

    Quote Originally Posted by Mike Pliam View Post
    Thanks Arjay.

    Is this better?
    Code:
                using (TextWriter WriteFileStream = new StreamWriter(@"patients12.xml"))
                {
                    XmlSerializer listObj = new XmlSerializer(typeof(List<Profile>));
                    XmlSerializerNamespaces nms = new XmlSerializerNamespaces();
                    nms.Add("", "");
                    listObj.Serialize(WriteFileStream, list, nms);
                    WriteFileStream.Close();
                }
    As a C# newbie I'm unclear as how to check for memory leaks. Or does C# take care of such things?
    Technically, there are no leaks, but you can run out of underlying system resources before the GC kicks in. For example, if you access a database in a tight loop with SqlConnection and SqlCommand, you can quickly reach a connection limit if you don't close the connection. I think the default is 100 connections to be open at one time. It is similar for file (handles). With files, it will drive you crazy to be done using a file and then try to access it later in code only to find that it is still in use.

    I make it a habit to use a using block everytime I can use one. In fact, I'd recommend attempting to put all new framework objects that you aren't familiar with inside a using block. If the object hasn't implemented IDisposable, then you'll get a compile error (so you know you can't use a using block for that object).

    Lastly, I like to think of IDisposable and the using block as the C#'s equivalent to a C++ destructor (it's not exactly the same, but the results are similar).

  5. #5
    Join Date
    May 2002
    Posts
    1,798

    Re: How to convert xml deserialized object to array

    Good information. Thanks.
    mpliam

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured