XmlRoot attribute serialization to a file

979 views Asked by At

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.

1

There are 1 answers

0
Alex On BEST ANSWER

You can remove the [XmlRoot(...)] attribute from the SubTemplate class.

There are a few possible solutions:

  1. Using [XmlArray] and [XmlArrayItem] attributes:

    Add these attributes to the Accounts member of the TemplateClass:

    public class TemplateClass
    {
        [XmlArray("Accounts")]
        [XmlArrayItem("Account")]
        public List<SubTemplate> Accounts;
    }
    
  2. Using the [XmlType] attribute:

    You can use this attribute instead on the originally used [XmlRoot] on the SubTemplate class.

    [XmlType("Account")]
    public class SubTemplate
    {
        public string Name;
        public string Region;
    }
    

Both of these will produce the following output:

<?xml version="1.0" encoding="utf-8"?>
<TemplateClass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Accounts>
    <Account>
      <Name>First name</Name>
      <Region>First region</Region>
    </Account>
    <Account>
      <Name>Second name</Name>
      <Region>Second region</Region>
    </Account>
  </Accounts>
</TemplateClass>