0

My model classes are:

public class Group
{
   public Employee Employee {get;set;}
}
public class Employee {
   public string Name {get;set;}
}

so after serialization my xml looks like this:

<Group>
  <Employee>
      <Name>Haley</Name>
  </Employee>
</Group>

but I would like it to be:

<Group>
  <Name>Haley</Name>
</Group>

So is there any attribute etc. to achieve that? I know I can do this using some code, but would be nice if there is some simplier solution. I saw the solution for lists and arrays (using [XmlElement] attribute), but looks like it doesn't work for non collection properties.

Przemysław
  • 206
  • 1
  • 7
  • You could rename `` to `` by adding `[XmlElement("Name")]` to `public Employee Employee {get;set;}` as shown in [Serialize/Deserialize different property names?](https://stackoverflow.com/a/19142954/3744182), them serialize the class `Employee` as a string value by marking `Name` with `[XmlText]` as shown in [C# - Xml Element with attribute and node value](https://stackoverflow.com/a/6696647/3744182). Is that what you want? – dbc May 20 '20 at 16:04
  • I don't think so, because what if there are more than one property inside? Like Name, Surname, Phone etc.? Then I couldn't use attribute just like `[XmlElement("Name")]` – Przemysław May 21 '20 at 06:52
  • Then could you clarify your problem please? Are you saying that `Employee` might have multiple properties and you want to bubble all of them up to the parent? – dbc May 21 '20 at 13:47
  • 1
    In any event I don't think there is a way to bubble multiple elements up to a parent node without using code -- e.g. surrogate properties or a DTO. – dbc May 21 '20 at 21:02
  • Ok, I thought so. Thanks then. – Przemysław May 22 '20 at 08:47

1 Answers1

0

Why not just

public class Group
{
    [XmlElement("Name")]
    public string name { get; set; }
    [XmlElement("Surname")]
    public string surname { get; set; }
    [XmlElement("phone")]
    public string phone { get; set; }
}

And just serialize this.

Bandook
  • 658
  • 6
  • 21