views:

31

answers:

2

I have two classes, A and B. A has an instance of B, and when serializing A, I want B to be at the same level as A and not a sub element.

So I want the resulting xml to become

    <a>
      <avalue>a</avalue>
      <bvalue>b</bvalue>
    </a>

This program puts B in it's own element as

    <a>
      <avalue>a</avalue>
      <b>
        <bvalue>b</bvalue>
      </b>
    </a>
public class A
{
    public string avalue = "a";
    public B b = new B();
}

public class B
{
    public string bvalue = "b";
}

class Program
{
    static void Main(string[] args)
    {
        var a = new A();
        var xml = new XmlSerializer(a.GetType());
        xml.Serialize(new StreamWriter(@"c:\temp\tmp.xml"), a);
    }
}

PS: This must have been asked before, but I'm not sure what to search for. My google-fu turns up empty...

Edit:

And I'm hoping to avoid the "wrapper" solution if possible:

public class A
{
    public string avalue = "a";

    [XmlIgnore]
    public B b { get; set; }

    [XmlElement("bvalue")]
    public string bvalue
    {
        get { return b.bvalue; }
        set { b.bvalue = value;  }
    }
}
A: 

you need to make B property and mark it with XMLAttribute.

Arseny
Doesn't seem to work: "XmlAttribute/XmlText cannot be used to encode complex types"
simendsjo
A: 

Arseny's answer is correct, although it is a little ambiguous, so here is what needs to change:

public class B
{
      [XmlAttribute]
      public string bvalue = "b";
}

And that outputs:

<?xml version="1.0" encoding="utf-8"?>
<A>
  <avalue>a</avalue>
  <b bvalue="b" />
</A>

Hope that's what you wanted.

Richard J. Ross III
Nope. I wan't bvalue as an element below avalue. I can solve it by creating a wrapper that flattens the structure if I have to, but I'd rather not :)
simendsjo
@Simpzon: Yes, I know that's possible, but isn't there any way of injecting the subclass elements to the parent?
simendsjo
@simendsjo: I already deleted this comment, because on the 2nd look it didn't seem to help anybody. I don't think there is a standard way for the thing you want to achieve, but I'm not the expert on this.
Simpzon