3

I can use [XmlIgnore] in order not to write elements, but how can I control this based on the content of a variable?

For example, I don't want to write XML element when the value is null.

[XmlRootAttribute("Component", IsNullable = true)]
public class Component {
    [XmlArrayAttribute("worlds_wola", IsNullable = true)]
    public List<Hello> worlds;      
    public int? a = null;
    public int? b = null;

    public Component()
    {
        worlds = new List<Hello>() {new Hello(), new Hello()}; 
    }
}

However, I got this XML.

<worlds_wola>
  ...
</worlds_wola>
<a xsi:nil="true" />
<b xsi:nil="true" />

Is there any way not to get an element that doens't have any value such as "<a/>" or "<b/>"?

prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

2

Include a property with name aSpecified and type bool and return false if a should not be part of the generated xml:

public bool aSpecified
{
    get { return this.a.HasValue; }
}

See also: https://stackoverflow.com/a/246359/295635

Community
  • 1
  • 1
Peter
  • 3,916
  • 1
  • 22
  • 43
1

Apparently the XmlSerializer supports ShouldSerialize methods:

You can also use custom serialization code with either IXmlSerializable or ISerializable.

For small classes this is easy enough but it can quickly get messy and fragile with larger cases.

You may also be able to use XmlSerializer constructor that takes attribute overrides depending on your circumstances:

StephenD
  • 3,662
  • 1
  • 19
  • 28