Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to serialise nested objects to XML

Posted on 2012-04-10
1
Medium Priority
?
385 Views
Last Modified: 2012-04-10
Hello,

I'm having troubles serializing nested objects.

Currently I have :
<?xml version="1.0" encoding="utf-8"?>
<FileConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Version>1.0</Version>
  <FileType>abc</FileType>
  <FileValue>abc.txt</FileValue>
</FileConfiguration><?xml version="1.0" encoding="utf-8"?>
<FileConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Version>1.0</Version>
  <FileType>abc1</FileType>
  <FileValue>abc1.txt.txt</FileValue>
</FileConfiguration>

Open in new window


But need:
<?xml version="1.0" encoding="utf-8"?>
<FileConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Files>
  <Version>1.0</Version>
  <FileType>abc</FileType>
  <FileValue>abc.txt</FileValue>
 </Files>
<Files>
  <Version>1.0</Version>
  <FileType>abc1</FileType>
  <FileValue>abc1.txt.txt</FileValue>
</Files>
</FileConfiguration>

Open in new window


Here is the code, I 've tried to nest a File object in FileConfiguration it turned into a mess.  Please provide some examples.  I'm not sure how to deserialize method will change as well.

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConfigurationFileCreator
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {

            FileConfiguration c = new FileConfiguration();
            c.FileType = "abc";
            c.FileValue = "abc.txt";
            c.Version = "1.0";


            FileConfiguration c1 = new FileConfiguration();
            c1.FileType = "Climate";
            c1.FileValue = "Climate.txt";
            c1.Version = "1.0";

            // Serialize the configuration object to a file
            FileConfiguration.Serialize("C:\\Configv1.xml", c, c1);

        }
    }


    #region -- FileConfiguration Class --
   
    [Serializable]
    
    public class FileConfiguration
    {
        string _Version;
        string _FileType;
        string _FileValue;

        public FileConfiguration()
        {
            _Version = "";
            _FileType = "";
            _FileValue = "";
        }



        public static void Serialize(string file, FileConfiguration c, FileConfiguration c1)
        {
            System.Xml.Serialization.XmlSerializer xs
               = new System.Xml.Serialization.XmlSerializer(c.GetType());
            StreamWriter writer = File.CreateText(file);
            xs.Serialize(writer, c);
            xs.Serialize(writer, c1);
            writer.Flush();
            writer.Close();
        }
//        public static Configuration Deserialize(string file)
//        {
//            System.Xml.Serialization.XmlSerializer xs
//               = new System.Xml.Serialization.XmlSerializer(
//                  typeof(Configuration));
//            StreamReader reader = File.OpenText(file);
//            Configuration c = (Configuration)xs.Deserialize(reader);
//            reader.Close();
//            return c;
//        }
        public string Version
        {
            get { return _Version; }
            set { _Version = value; }
        }
        public string FileType
        {
            get { return _FileType; }
            set { _FileType = value; }
        }
        public string FileValue
        {
            get { return _FileValue; }
            set { _FileValue = value; }
        }

    }
    #endregion
}

Open in new window


Thanks
0
Comment
Question by:AndyC1000
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 2000 total points
ID: 37826541
your class should look like this to acheive what you are trying to acheive:-

class Program
    {
        static void Main(string[] args)
        {
            var configuration = new FileConfiguration();

            configuration.AddFile("some", "test", "1.0");
            configuration.AddFile("other", "test2", "2.0");

            var fStream = new FileStream(Directory.GetCurrentDirectory() + @"\test.xml", FileMode.OpenOrCreate);

            var serializer = new NetDataContractSerializer();
            serializer.Serialize(fStream, configuration);

            fStream.Close();


            Console.Read();

        }

        
    }

    [DataContract]
    class FileConfiguration
    {
        private readonly IList<File> _lstFiles;

        public FileConfiguration()
        {
            _lstFiles = new List<File>();
        }

        public void AddFile(string name, string value, string version)
        {
            _lstFiles.Add(new File(name, version, value));
        }

        [DataMember]
        public File[] Files
        {
            get { return _lstFiles.ToArray(); }
        }
    }

    [DataContract]
    class File
    {
        [DataMember]
        public string FileName { get; private set; }

        [DataMember]
        public string FileVersion { get; private set; }

        [DataMember]
        public string FileValue { get; private set; }

        public File(string name, string version, string value)
        {
            FileName = name;
            FileVersion = version;
            FileValue = value;
        }
    }

Open in new window

0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

670 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