X.Otano
X.Otano

Reputation: 2169

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);
    }



}

Upvotes: 2

Views: 3717

Answers (2)

Mutlu Kaya
Mutlu Kaya

Reputation: 129

You should add a property named origenSpecified into FirmaElement class.

    [XmlIgnore]
    public bool origenSpecified
    {
        get
        {
            return !(string.IsNullOrEmpty(origen));
        }
    }

Upvotes: 1

Zharro
Zharro

Reputation: 809

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

Upvotes: 2

Related Questions