How can I rename class-names via Xml attributes?

Solution: Use [XmlType(TypeName=”g”)]

XmlRoot only works with XML root nodes as per the documentation (and what you would expect, given its name includes root)!

I was unable to get any of the other answers to work so kept digging…

Instead I found that the XmlTypeAttribute (i.e. [XmlType]) and its TypeName property do a similar job for non-root classes/objects.

e.g.

[XmlType(TypeName="g")]
class Song
{
    public string Artist;
    public string SongTitle;
}

Assuming you apply it to the other classes e.g.:

[XmlType(TypeName="a")]
class Artist
{
    .....
}

[XmlType(TypeName="s")]
class SongTitle
{
    .....
}

This will output the following exactly as required in the question:

<g>
  <a>Britney Spears</a>
  <s>I Did It Again</s>
</g>

I have used this in several production projects and found no problems with it.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)