3
I am 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 don’t value one of them, it’s null
When generating xml it does not generate the element
I would like it to generate even being empty or null
If I fill out var test = new Person { Cpf = "123", name = "so-and-so" } and have generated, it generates only
<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...
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;
}
}
Friend, look at my edition. I managed to solve using
ShouldSerialize
.– Miguel Angelo