You can control exactly what the serialization of your class to XML will look like with the interface IXmlSerializable. If you make your class Pessoa implement this interface, you can, in the method WriteXml, choose exactly the form it will be issued when it is serialized into XML. The code below shows an example of implementation 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())));
}
}
You are returning your class from a Webapi?
– joaoeduardorf
ViewModelwould be the option!– novic
@joaoeduardorf, I don’t understand the reason for your conversation. I have some class and I will serialize it using the class Xmlserializer of
C#, I believe that the way I obtain the data for it is not relevant. Please clarify?– Pedro Camara Junior
@Virgilionovic, relamente Viewmodel is an option, but if it is possible otherwise would be the ideal. =/
– Pedro Camara Junior
Sure @Pedrocamarajunior, I’ll put an example as an answer.
– joaoeduardorf