views:

60

answers:

3

Hello,

Have the following XML model

<A></A>
<B></B>
<C></C>
<D></D>

Also have three classes

class Foo1{
  public string A;
  public string B;
}
class Foo2{
  public string C;
  public string D;
}

class FooUnited{
  public Foo1 foo1;
  public Foo2 foo2;
}

The problem. I want to deserialize xml into object of FooUnited type. The brute-force idea is to manually select values from xml and initialize FooUnited object, but maybe there is a more elegant solution for that?

+1  A: 

Assuming you have a root element you can use a DTO to wrap up the differences:

public class MyDto {
    public string A {get;set;}
    public string B {get;set;}
    public string C {get;set;}
    public string D {get;set;}

    public FooUnited GetObject() {
        return new FooUnited {
            foo1 = new Foo1 { A = this.A, B = this.B },
            foo2 = new Foo2 { C = this.C, D = this.D },
        };
    }
}
Marc Gravell
A: 

No, as far as I know, you cannot do that, automatically. To use XmlSerialization (built into .NET) the hierarchy in the object model must match the hierarchy in the document.

With your class structure, it would be like this:

<FooUnited>
    <Foo1>
        <A></A> 
        <B></B> 
    </Foo1>
    <Foo2>
        <C></C> 
        <D></D> 
    </Foo2>
</FooUnited>

You would need a memento or DTO, as MArc described.

Cheeso
A: 

I'd be tempted to create a set of immutable classes and use XPath to parse the XML and populate those classes.

Alternatively you could use something like XStream if you control both serialization and deserialization.

Fortyrunner