views:

60

answers:

3

How do I get the attributes to the inner element rather than root element?

[XmlRoot("Root")]
public class Test
{
    string type=null;
    int value=0;
    public string Type
    {
        get { return type; }
        set { type=value; }
    }
    [XmlAttribute]
    public int Value
    {
        get { return type; }
        set { type=value; }
    }
}

will result into

<Root Value="">
    <Type>
    </Type>
</Root>

However I want

<Root >
    <Type Value="">
    </Type>
</Root>

Please help me out. Thanks in advance.

A: 
[XmlRoot("Root")]
public class Test
{
    TypeClass type=null;
    [XmlElement("Type")]
    public TypeClass Type
    {
       get{return type;}
       set{type=value;}
    }
}
[XmlRoot("Type")]
public class TypeClass
{
   int _value=0;
   [XMlAttribute]
   public int Value
   {
      get{return _value;}
      set{_value=value;}
   }
}

try this

ArsenMkrt
whitespace, please!
Danny
+1  A: 

The XmlSerializer is not super customizable. The closest you can get to achieving this (without resorting to custom serialization) is a wrapper class:

[XmlRoot("Root")]
public class Test
{
    public TypeData Type { get; set; }

    // ...
}

class TypeData
{
    public string Data { get; set; }

    [XmlAttribute]
    public int Value { get; set; }
}

In that case, you'll end up with:

<Root>
  <Type Value="">
    <Data>...</Data>
  </Type>
</Root>
bobbymcr
+2  A: 

XmlSerializer is intended to be a natural map between the object model and the xml; the answer, then, is to structure your DTO the same as your xml. In this case, by wrapping Test in a second object:

public class Root {
    public Test Type {get;set;}
}

The alternative is implementing IXmlSerializable, but that is effort, and easy to get wrong. It isn't uncommon to require a separate object representation for serialization purposes - it shouldn't be assumed that your "regular" business/data objects are necessarily directly suitable for serialization.

Marc Gravell
+1 for "structure your DTO to fit your xml"
Nader Shirazie