1

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

0
[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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.