Home > front end >  Serialize two lists of objects into an XML file
Serialize two lists of objects into an XML file

Time:11-15

Trying to create an XML file of the following structure:

<Objects>
    <ArrayOfObject1>
        <Object1>
        <Object1>
    </ArrayOfObject1>
    <ArrayOfObject2>
        <Object2>
        <Object2>
    </ArrayOfObject2>
</Objects>

Is there any way to achieve this using the XmlSerializer? I'm aware that the following code snippet can be used to generate an XML file that has a root node of ArrayOfObject1 and elements corresponding to every object in the list; I'd just like to extend this to have a different root node, and an array of each object within it.

XmlSerializer serializer = new XmlSerializer(typeof(List<Object1>));

Of course, it may be best practice to have two different XML files, but I'm just trying to find out if there's an acceptable/sensible way to have two arrays of objects represented in a single file.

Thanks!

CodePudding user response:

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);
            XmlSerializer serializer = new XmlSerializer(typeof(Objects));

            Objects objects = new Objects()
            {
                objects1 = new List<Object1>()
                {
                    new Object1(), new Object1()
                },
                objects2 = new List<Object2>()
                {
                    new Object2(), new Object2()
                }

            };

            serializer.Serialize(writer, objects);

        }
 
    }
    public class Objects
    {
        [XmlArray("ArrayOfObject1")]
        [XmlArrayItem("Object1")]
        public List<Object1> objects1 { get; set; }
        [XmlArray("ArrayOfObject2")]
        [XmlArrayItem("Object2")]
        public List<Object2> objects2 { get; set; }

    }
    public class Object1
    {

    }
    public class Object2
    {

    }
}
  • Related