Let’s look over the following code:
public class Car
{
public string Id { get; set; }
}
public class City
{
[XmlArray("Cs")]
[XmlArrayItem("C")]
public List<Car> RegisterCars { get; set; }
}
...
XmlSerializer serializer = new XmlSerializer(typeof(City));
serializer.Serialize(writer, city);
Output:<city>
<Cs>
<c>
<id>1</id>
<c>
<c>
<id>2</id>
<c>
<Cs>
</city>
Even if the code compiles, works perfectly, there is a small thing that can affect us. Because we use XmlArrayItem attribute, each node from the list will be named “C”. If we will need to deserialize only a C node then we will have a surprise.This cannot be done with the default XmlSerializer class.
XmlSerializer serializer = new XmlSerializer(typeof(Car));
serializer.Deserialize("<c><id>1</id></c>");
This will expect a node named “Car”, that cannot be found there.Because of this, when we need to control the name of the nodes from a list and I recommend to not use the XmlArrayItem. A better approach is with [XmlRoot(ElementName = "c")] on the Car class. Using this approach, we will be able to deserialize a child node of the list without having to deserialize all the list.
The final code will look like this:
[XmlRoot(ElementName = "c")]
public class Car
{
public string Id { get; set; }
}
public class City
{
[XmlArray("Cs")]
public List<Car> RegisterCars { get; set; }
}
Even if this is a small thing, on a big project this can affect how different components deserialize the content. Deciding how items need to be serialized is an important step that needs to be done from the beginning.
0 comments:
Post a Comment