1

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



}
X.Otano
  • 2,079
  • 1
  • 22
  • 40
  • What's the harm in showing the attribute origen with no value? XML was designed to handle data formats, with or without values provided. – Tony Abrams Mar 17 '17 at 10:51
  • Possible duplicate of [Xml serialization - Hide null values](http://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values) – Tony Abrams Mar 17 '17 at 10:54

2 Answers2

2

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

Community
  • 1
  • 1
Zharro
  • 819
  • 1
  • 11
  • 23
1

You should add a property named origenSpecified into FirmaElement class.

    [XmlIgnore]
    public bool origenSpecified
    {
        get
        {
            return !(string.IsNullOrEmpty(origen));
        }
    }
Mutlu Kaya
  • 129
  • 7