3

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



}
2
  • What's the harm in showing the attribute origen with no value? XML was designed to handle data formats, with or without values provided. Commented Mar 17, 2017 at 10:51
  • Possible duplicate of Xml serialization - Hide null values Commented Mar 17, 2017 at 10:54

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

You should add a property named origenSpecified into FirmaElement class.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.