I'm generating an xml through an existing class, for example
[XmlRoot("pessoa")]
public class pessoa
{
//[CPFValidation]
[XmlElement("cpf")]
public virtual string cpf { get; set; }
[XmlElement("nome")]
public virtual string nome{ get; set; }
[XmlElement("telefone")]
public virtual string telefone{ get; set; }
}
And I'm using the following code to generate xml
public static string CreateXML(Object obj)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UnicodeEncoding(false, false);
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (StringWriter textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
serializer.Serialize(xmlWriter, obj);
}
return textWriter.ToString();
}
}
Seeing that there are 3 properties: cpf, name and phone
When I do not assign value to one of them, it gets null
When generating the xml it does not generate the element
I would like it to generate even though it is empty or null
If I fill out var test = new Person { cpf="123", name="so and so"} and have it generated, it only generates
<cpf>123</cpf>
<nome>fulano</nome>
E não gera o elemento <telefone></telefone>
So I used an anottation to set the values for me ... srsrsrsrs
public class XMLAtributos : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) return false;
IList<PropertyInfo> propriedades = new List<PropertyInfo>(value.GetType().GetProperties());
foreach (PropertyInfo propriedade in propriedades)
{
object valor = propriedade.GetValue(value, null);
if (valor == null)
{
propriedade.SetValue(value, " " ,null);
}
}
return true;
}
}