0
votes

Is there anyway to add a XML Root Element or "Wrapper" in the XmlSerializer when I serialize an object?

The XML I am looking for would be something like this:

<Groups>
    <Group method="ModifySubGroups" ID="1234" PIN="5678">
        <SubGroup action="Delete" number="95">
            <Name>Test</Name>
        </SubGroup>
    </Group>
</Groups>

I have two classes, Group and SubGroup. Group contains a generic list of SubGroups. It works great, but I don't have the XML Root "Groups". Using the two classes Group and SubGroup produces this:

<Group method="ModifySubGroups" ID="1234" PIN="5678">
   <SubGroup action="Delete" number="95">
       <Name>Test</Name>
   </SubGroup>
</Group>

The only way I could get it to work was to create another class "Groups" that contained Group. So now I have three classes, Groups, Group, and SubGroup. Groups contains Group and Group contains SubGroup.

Any other ideas?

2

2 Answers

4
votes

You don't normally use XML serialization to make XML pretty. If you need a root container element, then you need to have a root container object, and serialize that instead of Group object.

You can however serialize an array of Group object

void Main()
{
    var g = new Group();
    g.SubGroups.Add(new SubGroup {Name = "aaa"});

    var ser = new XmlSerializer(typeof(Group[]), new XmlRootAttribute("Groups"));
    using (var w = new StringWriter())
    {
        ser.Serialize(w, new Group[] {g});
        w.ToString().Dump();
    }
}

public class Group
{
    [XmlElement("SubGroup")]
    public List<SubGroup> SubGroups = new List<SubGroup>();
}

public class SubGroup
{
    public string Name;
}

Naturally this means that deserialize code needs to either magically know that there is always one and only one Group element or assume that there could be 0 or more. Honestly I don't see much point in doing this unless you actually want to serialize collection of groups. It would just add confusion.

0
votes

EDIT: if you really want to comply to vendors schema you are starting from wrong point. You do not need to implement classes like this at all, all you do instead is taking an vendors XSD and use xsd utility provided with Visual Studio to generate .net classes from your schema, you can also choose which way you want serialize objects - using XmlSerializer or DataContractSerializer ( which gives you better flexibility i would say )

NOTE : you can use some tools to generate xsd from your xml if you do not have one and do not know how to write it on yourself

You can use XmlRootAttribute in order to specify custom XML Root

Also when you serialize collection you can specify wrapper - see Array Serializing