Reputation: 2624
We have the followig code:
[Serializable]
public class Class1
{
[XmlElement("description")]
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
var list = new List<Class1> {new Class1() {Description = "Desc1"}, new Class1() {Description = "Desc2"}};
var serializer = new XmlSerializer(typeof(List<Class1>), new XmlRootAttribute("root"));
var ms = new MemoryStream();
serializer.Serialize(ms, list);
ms.Position = 0;
var result = new StreamReader(ms).ReadToEnd();
}
}
after execution we will have the following in 'result' variable:
<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Class1>
<description>Desc1</description>
</Class1>
<Class1>
<description>Desc2</description>
</Class1>
</root>
The question is: how to change xml elements name from 'Class1' to 'Item1' without changing class name?
Upvotes: 17
Views: 31397
Reputation: 109200
Use an XmlTypeAttribute
on the class as well:
[XmlType(TypeName="ElementName")]
[Serializable]
public class Class1 { ...
EDIT: Updated from XmlRootAttribute
to XmlTypeAttribute
. The former works where the type being passed to the serialiser is the attributed type (Class1
here), but not when there is a wrapping type (List<Class1>
here). That XmlType
works is not clear from the documentation (my emphasis):
Controls the XML schema that is generated when the attribute target is serialized by the XmlSerializer.
Credit to Bala R's answer.
Upvotes: 6
Reputation: 109027
You can use XmlTypeAttribute.TypeName
for this.
Try this for you Class1
definition
[XmlType(TypeName = "Item1")]
[Serializable]
public class Class1
{
[XmlElement("description")]
public string Description { get; set; }
}
Upvotes: 44