0

XmlSerializer encodes the type name for arrays, but not for scalars. Sue, a Staff/Person, has the Person element. Yolanda, a Manager/Person, does not. I want both Name elements within a Person element.

I have looked for a way to configure an XmlElement, but I have not been successful.

I wish that a query for Person would return Yolanda and Sue.

using System.Xml.Serialization;
public class Person {
    public string Name;
    public Person() { }
    public Person(string name) { this.Name = name; }
}

public class Group {
    public Person Manager;
    public Person[] Staff;
    public Group() { }
    public Group(string manager, string staff) {
        this.Manager = new Person(manager);
        this.Staff = new Person[] { new Person(staff) 
};


    public void testXmlSerializeFromMicrosoft() {
        XmlSerializer serializer = new XmlSerializer(typeof(Group));
        serializer.Serialize(Console.Out, new Group("Yolanda", "Sue"));
    }

---actual output---

...
<Manager>
  <Name>Yolanda</Name>
</Manager>
<Staff>
  <Person>
    <Name>Sue</Name>
  </Person>
</Staff>

--- desired output ---

 <Manager>
   <Person>                           //desired element
     <Name>Yolanda</Name>
   </Person>
 </Manager>
 <Staff>
   <Person>
     <Name>Sue</Name>
   </Person>
 </Staff>
  • Your question is somewhat unclear. Are you looking to change the XML element name used for the `Manager` property? If so see [Serialize/Deserialize different property names?](https://stackoverflow.com/a/19142954). You might also be looking for [Rename class when serializing to XML](https://stackoverflow.com/a/36804496/3744182). If neither of those answer your question, can you [edit] it to show the **required** XML as well as the **current** XML? – dbc Apr 07 '18 at 18:56
  • This is not possible: the `XmlSerializer` cannot add elements. However, this can be done with the help of a custom `XmlWriter`. Or you need to implement the `IXmlSerializable` interface. – Alexander Petrov Apr 08 '18 at 14:51
  • I suppose you could introduce some sort of container object using the trick from [Most elegant xml serialization of Color structure](https://stackoverflow.com/a/4322461/3744182). – dbc Apr 08 '18 at 16:53

0 Answers0