0

I am trying to create a generic class structure to save lists with various subitems in an xml file as XML attributes. Each subitem has Name (string) and a Value (double).

An example: The XML of two Lists - frame 1 and frame 2 - should look like this shown above. The frame1 is a List of the class rec. The class rec always contains multiple pairs of parameters and their values. In frame1 the class rec contains the parameters car, factory and height. And in frame2 book and page.

    <frame1>
      <rec car="0" factory="1" height="2" />
      <rec car="1" factory="4" height="2" />
      <rec car="2" factory="4" height="3" />
      <rec car="3" factory="5" height="2" />
    </frame1>
    <frame2>
      <rec book="0" page="1" />
      <rec book="1" page="4" />
      <rec book="2" page="4" />
      <rec book="3" page="5" />
    </frame2>

This is only an example. I do not want to create different classes with different properites for each "frame" List. I want to solve the problem with one class "rec" as the subitems are always changing. Is there a way to create this?

Thank you in advance

rahrah
  • 1
  • 1

1 Answers1

0

I think you can use a code like this: lists is an object[][], so not any generic types needed.

using System.Xml.Linq;

...

var lists = new[]
                {
                    new object[]
                        {
                            new ClassA("0", "1", "2"), new ClassA("1", "4", "2"), new ClassA("2", "4", "3"),
                            new ClassA("3", "5", "2"),
                        },
                    new object[]
                        {
                            new ClassB("0", "1"), new ClassB("1", "4"), new ClassB("2", "4"),
                            new ClassB("3", "5"),
                        }
                };

var xml = new XDocument(new XElement("Root"));
for (var i = 0; i < lists.Length; i++)
{
    var eFrame = new XElement($"frame{i}");
    var list = lists[i];
    foreach (var obj in list)
    {
        var eRec = new XElement("rec");
        var props = obj.GetType().GetProperties();
        foreach (var prop in props)
        {
            eRec.SetAttributeValue(prop.Name, prop.GetValue(obj).ToString());
        }

        eFrame.Add(eRec);
    }

    xml.Root.Add(eFrame);
}

Result will be something like this as xml object:

<Root>
  <frame0>
    <rec car="0" factory="1" height="2" />
    <rec car="1" factory="4" height="2" />
    <rec car="2" factory="4" height="3" />
    <rec car="3" factory="5" height="2" />
  </frame0>
  <frame1>
    <rec book="0" page="1" />
    <rec book="1" page="4" />
    <rec book="2" page="4" />
    <rec book="3" page="5" />
  </frame1>
</Root>
shA.t
  • 16,580
  • 5
  • 54
  • 111