1

I have the following code:

[Serializable]
[XmlRoot("Database")]
public class SqlDatabase
{
    public List<SqlTable> Tables { get; private set; }
}

If I use XmlSerializer without any custom attribute, generated XML persists list hierarchy:

<Database>
  <Tables>
    <SqlTable Name="Table1" />
    <SqlTable Name="Table2" />
  </Tables>
</Database>

However, I want to change the element name "SqlTable" to "Table". I tried to use XmlElement attribute on the list

[Serializable]
[XmlRoot("Database")]
public class SqlDatabase
{
    [XmlElement("Table")]
    public List<SqlTable> Tables { get; private set; }
}

The name is changed but the hierarchy is flattened:

<Database>
  <Table Name="Table1" />
  <Table Name="Table2" />
</Database>

Then I tried XmlArray attribute, which changes the name of the list but not the elements within:

[Serializable]
[XmlRoot("Database")]
public class SqlDatabase
{
    [XmlArray("Foo")]
    public List<SqlTable> Tables { get; private set; }
}

Results in

<Database>
  <Foo>
    <SqlTable Name="Table1" />
    <SqlTable Name="Table2" />
  </Foo>
</Database>

I tried to combine these two and there is an exception saying they can't be used together.

So the question is, is there a simple way to change the element name without flattening the hierarchy?

NS.X.
  • 2,072
  • 5
  • 28
  • 55
  • 2
    I think this answer will solve your problem. http://stackoverflow.com/a/6462300/1181408 – cgotberg Jul 23 '13 at 21:28
  • yes, use a combination of XmlArray and XmlArrayItem attributes as @cgotberg suggests – DaveRead Jul 23 '13 at 21:34
  • @cgotberg Thanks, it is the answer I am looking for. Didn't see it because the title of that question seemed irrelevant. – NS.X. Jul 23 '13 at 21:41
  • 1
    possible duplicate of [How to use XmlElementAttribute for List?](http://stackoverflow.com/questions/6462091/how-to-use-xmlelementattribute-for-listt) – NS.X. Jul 24 '13 at 08:26

0 Answers0