Mateusz
Mateusz

Reputation: 116

Deserialize XmlElement with part name

This is my sample XML:

<outbound>
      <leg0 Code="aaa" RetCode="ccc"/>
      <leg1 Code="bbb" RetCode="ddd"/>
</outbound>

Is it possible to use somehow XmlElement (I'm using XmlSerializer) to deserialize leg0 and leg1 to one object type?

My object's looks like that:

  public class FlightInfo
  {
    [XmlElement(ElementName = "outbound")]
    public Outbound Outbound { get; set; }
  }

  public class Outbound
  {
    [XmlElement(ElementName = "leg")]
    public List<Leg> Leg { get; set; }
  }

  public class Leg
  {
    [XmlAttribute(AttributeName = "Code")]
    public string Code{ get; set; }
    [XmlAttribute(AttributeName = "RetCode")]
    public string ReturnCode{ get; set; }
  }

My problem is to deserialize elements leg0 and leg1 to Leg object. Can anybody give my a hint?

Upvotes: 1

Views: 414

Answers (2)

Tim Rutter
Tim Rutter

Reputation: 4679

Having every leg with a different element name is the problem here. If its possible could you instead do something like:

<outbound>
  <leg Index=0 Code="aaa" RetCode="ccc"/>
  <leg Index=1 Code="bbb" RetCode="ddd"/>
</outbound>

And the issue goes away.

If you're stuck with the format could you do some "preprocessing". Search and replace "legn" with "leg Index=\"n\"" which would produce the format above that you could then deserialize.

The problem you have as it is, is that when C# Serializes a Leg it needs to know which node name to give - how will it know? You've lost the index.

Upvotes: 2

Lee
Lee

Reputation: 584

I don't think you can deserialize different element names to the same property. What you could do is have a separate property which would join both lists, so you have an easier way to access it. Something as follows (not tested but should work):

public class Outbound {

[XmlElement(ElementName = "leg0")]
public List<Leg> leg0 { get; set; }

[XmlElement(ElementName = "leg1")]
public List<Leg> leg1 { get; set; }

[XmlIgnore] //You don't want to deserialize this property
public List<Leg> AllLegs { 
get
    {
        return leg0.Join(leg1);
    }
                          }

}

Upvotes: 0

Related Questions