You can control exactly how your class will serialize to XML with the IXmlSerializable
. If you make your Pessoa
class implement this interface, you can, in the WriteXml
method, choose exactly what form it will emit when it is serialized to XML. The code below shows an implementation example for your scenario.
public class PtStackOverflow_209719
{
public class Pessoa : IXmlSerializable
{
public string nome { get; set; }
public int idade { get; set; }
public Endereco endereco { get; set; }
public override string ToString()
{
return string.Format("Pessoa[nome={0},idade={1},endereco={2}]",
this.nome, this.idade, this.endereco);
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement("Pessoa");
this.nome = reader.ReadElementContentAsString();
this.idade = reader.ReadElementContentAsInt();
this.endereco = new Endereco();
this.endereco.logradouro = reader.ReadElementContentAsString();
this.endereco.numero = reader.ReadElementContentAsString();
reader.ReadEndElement();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("nome", this.nome);
writer.WriteElementString("idade", this.idade.ToString());
writer.WriteElementString("logradouro", this.endereco.logradouro);
writer.WriteElementString("numero", this.endereco.numero);
}
}
public class Endereco
{
public string logradouro { get; set; }
public string numero { get; set; }
public override string ToString()
{
return string.Format("Endereco[logradouro={0},numero={1}]",
this.logradouro, this.numero);
}
}
public static void Test()
{
MemoryStream ms = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Pessoa));
Pessoa p = new Pessoa
{
nome = "Fulano de Tal",
idade = 33,
endereco = new Endereco
{
logradouro = "Avenida Brasil",
numero = "123"
}
};
xs.Serialize(ms, p);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
ms.Position = 0;
Pessoa p2 = xs.Deserialize(ms) as Pessoa;
Console.WriteLine(p);
Console.WriteLine();
ms = new MemoryStream();
XmlSerializer xs2 = new XmlSerializer(typeof(Pessoa[]));
xs2.Serialize(ms, new Pessoa[] { p, p2 });
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
ms.Position = 0;
Pessoa[] ap = xs2.Deserialize(ms) as Pessoa[];
Console.WriteLine(string.Join(" - ", ap.Select(pp => pp.ToString())));
}
}