c# – Generate xml through a class, even without a property value

Question:

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 the 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 assign a value to one of them, it becomes null

When generating the xml it does not generate the element

I would like it to generate even if it is empty or null

If I fill in var test = new Person { cpf = "123", name = "so and so" } and have it generate, it just 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;
        }
    }

Answer:

Tell the serializer that this element can be serialized null (empty tag)

[XmlRoot("pessoa")]
public class pessoa
{
    //[CPFValidation]
    [XmlElement("cpf", IsNullable = true)]
    public virtual string cpf { get; set; }

    [XmlElement("nome", IsNullable = true)]
    public virtual string nome{ get; set; }

    [XmlElement("telefone", IsNullable = true)]
    public virtual string telefone{ get; set; }
}

If you have correctly described your problem this should solve it.

There are more parameters that can be passed to customize your serialization see the documentation here

Scroll to Top