Reputation: 104741
I want to serialize/deserialize the following types:
// The "NameEntity" element shouldn't appear in the XML
public class NameEntity
{
[XmlElement("name")]
public string Name { get; set; }
}
[XmlRoot("names")]
public class Names : List<NameEntity>
{
}
I want the serialized XML to match the following scheme:
<?xml version="1.0" encoding="utf-8" ?>
<names>
<name>Charlie</name>
<name>Robert</name>
<name>Nick</name>
</names>
In fact, the output XML is:
<names>
<NameEntity>
<name>Charlie</name>
</NameEntity>
...
</names>
Is this possible with one of the XML attributes in .NET or I'll have to implement IXmlSerializable
?
Upvotes: 2
Views: 72
Reputation: 50225
You need a mixture of the XmlType Attribute and the XmlText Attribute like so...
// The "NameEntity" element shouldn't appear in the XML
[XmlType("name")]
public class NameEntity
{
[XmlText]
public string Name { get; set; }
}
[XmlRoot("names")]
public class Names : List<NameEntity>
{
}
public class SO
{
[Test]
public void NameEntitySerialization()
{
var name = new NameEntity() { Name = "Austin" };
var serialized = <YOUR SERIALIZATION CODE HERE>
Console.WriteLine(serialized);
Assert.AreEqual("<name>Austin</name>", serialized);
}
[Test]
public void ListSerialization()
{
var names = new Names();
names.Add(new NameEntity() {Name = "Austin"});
var serialized = <YOUR SERIALIZATION CODE HERE>
Console.WriteLine(serialized);
Assert.AreEqual("<names>\r\n <name>Austin</name>\r\n</names>",
serialized);
}
}
Upvotes: 2