Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSerialization ignore string attribute if empty

i want a class to be serializated to XML. It works, but a string attribute "origen" is allways being serialized as string , also when is empty. I want the serializer to avoid include it inside the XML when it is null

The class is FirmaElement , for example:

FirmaElement firma= new FirmaElement();
firma.Value="HITHERE";
firma.origen=String.Empty;

EXPECTED RESULT

string x= Serialize(FirmaElement);
x="<Firma>HITHERE</Firma>";

FirmaElement firma= new FIrmaElement();
firma.Value="HITHERE";
firma.origen="OK";

EXPECTED RESULT

string x= Serialize(FirmaElement);
x="<Firma origen='ok'>HITHERE</Firma>";

Code

 [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://gen/ces/headers/CesHeader")]
[System.Xml.Serialization.XmlRoot("Firma")]
public class FirmaElement
{
    public FirmaElement() { }
    string _origen = String.Empty;
    string _value = String.Empty;


    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string origen
    {
        get { return _origen; }
        set { _origen = value; }
    }

    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value
    {
        get { return _value; }
        set { _value = value; }
    }


    public override string ToString()
    {
        return this.Value;
    }


    //IS THIS CORRECT? SHould i override something??
    public  string Serialize()
    {
        XmlAttributeOverrides xOver = new XmlAttributeOverrides();
        XmlAttributes attrs = new XmlAttributes();

        /* Setting XmlIgnore to false overrides the XmlIgnoreAttribute
           applied to the Comment field. Thus it will be serialized.*/
        attrs.XmlIgnore = String.IsNullOrEmpty(origen);
        xOver.Add(typeof(string), "origen", attrs);

         I DONT KNOW WHAT TO PUT HERE, IT'S CORRECT??

        //XmlSerializer xSer = new XmlSerializer(typeof(XmlTypeAttribute), xOver);
    }



}
like image 853
X.Otano Avatar asked Apr 21 '26 04:04

X.Otano


2 Answers

You can specify whether particular property should be serialized or not with help of method with name ShouldSerialize{PropertyName}. Check this answer out.

like image 190
Zharro Avatar answered Apr 22 '26 18:04

Zharro


You should add a property named origenSpecified into FirmaElement class.

    [XmlIgnore]
    public bool origenSpecified
    {
        get
        {
            return !(string.IsNullOrEmpty(origen));
        }
    }
like image 26
Mutlu Kaya Avatar answered Apr 22 '26 19:04

Mutlu Kaya