Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
Marcom Avatar asked May 28 '26 23:05

Marcom


2 Answers

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"));  
like image 55
Steven Jeuris Avatar answered May 31 '26 13:05

Steven Jeuris


If value is always ignored, you're better off assigning the attribute directly to the member.

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

If value is conditionally ignored, I suspect you're better off removing the element from the root class before serializing.

As for your code, I suspect (I may be wrong because I haven't try it yet!) the following is sufficient:

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

Update: I tested the above code. It works. :D Update again: it should be Items instead of Item, because Value is in Items. Or if you like it the other way, it could be Value in Item and Item all the way.

like image 35
Fun Mun Pieng Avatar answered May 31 '26 11:05

Fun Mun Pieng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!