I have the following code serializing an object into a file:
TemplateClass item = new TemplateClass();
// Fill in item
XmlSerializer writer = new XmlSerializer(typeof(TemplateClass));
using (StreamWriter file = new StreamWriter(filePath))
{
writer.Serialize(file, item);
}
where TemplateClass is defined as follows:
public class TemplateClass
{
public List<SubTemplate> Accounts;
}
[XmlRoot(ElementName = "Account")]
public class SubTemplate
{
public string Name;
public string Region;
}
I was expecting the XmlRoot attribute to write Account in place of SubTemplate in the file. But the file output currently looks like this:
<TemplateClass>
<Accounts>
<SubTemplate>
<Name>SampleName</Name>
<Region>SampleRegion</Region>
</SubTemplate>
</Accounts>
</TemplateClass>
How can I change my code such that the output looks like:
<TemplateClass>
<Accounts>
<Account>
<Name>SampleName</Name>
<Region>SampleRegion</Region>
</Account>
</Accounts>
</TemplateClass>
I dont want to change the name of the SubTemplate class to Account though.
You can remove the
[XmlRoot(...)]
attribute from theSubTemplate
class.There are a few possible solutions:
Using
[XmlArray]
and[XmlArrayItem]
attributes:Add these attributes to the
Accounts
member of theTemplateClass
:Using the
[XmlType]
attribute:You can use this attribute instead on the originally used
[XmlRoot]
on theSubTemplate
class.Both of these will produce the following output: