Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Xml Deserializing - Preserving the child order

I have an Xml that looks something like this (simplified example):

<childrenNode>
   <myClass1>
      <someValues />
   </myClass1>
   <myClass2>
      <someOtherValues />
   </myClass2>
   <myClass1>
      <someValues />
   </myClass1>
   <myClass2>
      <someOtherValues />
   </myClass2>
   <myClass1>
      <someValues />
   </myClass1>
</childrenNode>

When parsing it, I use a class that look something like this:

public class childrenNode
{
   public myClass1[] myClass1 { get; set; }
   public myClass2[] myClass2 { get; set; }
}

The problem with this is that I loose the ordering. I.e I need to know that the second myClass1 is the third item of the array. Ideally, I'd serialize the Xml into something like this in order to preserve the ordering:

public class childrenNode
{
   public object[] child { get; set; }
}

The Xml is outputted by a third party application, so I have no chance of changing its layout.

Any suggestions of what alternatives I have? The Xml's are in reality massive so parsing it using an XmlReader will be a lot of work.

like image 353
BlueVoodoo Avatar asked Sep 15 '25 08:09

BlueVoodoo


1 Answers

You could map the nodes with the XmlElementAttribute msdn

public class childrenNode
{
   [XmlElement("myClass1", typeof(myClass1))]
   [XmlElement("myClass2", typeof(myClass2))]
   public BaseNode[] nodes { get; set; }
}

public class BaseNode
{

}

public class myClass1: BaseNode
{
}

public class myClass2: BaseNode
{
}
like image 110
Stefan Avatar answered Sep 17 '25 02:09

Stefan