Search code examples
c#xmlserializationxml-serializationxmlignore

XmlIgnore not working


I have an object that I am trying to serialise and the output looks something like this:

 <root>
  <Items>
    <Item>   
      <Value> blabla </Value>
    </Item>  
  </Items>

where Item is a class that the class root uses.

[Serializable]
[XmlType("root")]
public class Root { }

[Serializable]
[XmlInclude(typeof(Item))]
public class Items {}

[Serializable]
public class Item 
{ 
    [XmlElement("Value")]
    public string DefaultValue { get; set; }
}

In some cases I want to ignore the value of value and I have this code

 var overrides = new XmlAttributeOverrides();
 var attributes = new XmlAttributes { XmlIgnore = true };
 attributes.XmlElements.Add(new XmlElementAttribute("Item"));                  
 overrides.Add(typeof(Item), "Value", attributes);               
 var serializer = new XmlSerializer(typeof(root), overrides);

but the value is still written in the output.

What am I doing wrong?


Solution

  • Now that you updated your question, it is obvious what you are doing wrong. :)

    [Serializable]
    public class Item 
    { 
        [XmlElement("Value")]
        public string DefaultValue { get; set; }
    }
    

    You should pass the name of the property instead of the xml name, as specified in the documentation.

    overrides.Add(typeof(Item), "DefaultValue", attributes);
    

    ... instead of ...

    overrides.Add(typeof(Item), "Value", attributes);
    

    Also as specified in Fun Mun Pieng's answer, you shouldn't add the XmlElementAttribute anymore, so remove the following line:

     attributes.XmlElements.Add(new XmlElementAttribute("Item"));