开发者

XmlIgnore not working

I have an object that I am trying to serialise and the output looks something 开发者_StackOverflow社区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?


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


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.


I believe XMLIgnore attribute should be used to decorate a public member of a class which has been decorated with XmlSerializable attribute, that way would work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜