c# - XmlIgnore 不起作用

标签 c# xml serialization xml-serialization xmlignore

我有一个我正在尝试序列化的对象,输出看起来像这样:

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

其中 Item 是类根使用的类。

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

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

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

在某些情况下我想忽略value的值而我有这段代码

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

但该值仍写入输出中。

我做错了什么?

最佳答案

现在您更新了问题,很明显您做错了什么。 :)

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

您应该按照指定的方式传递属性名称而不是 xml 名称 in the documentation .

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

...而不是...

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

同样如 Fun Mun Pieng 的回答中所述,您不应再添加 XmlElementAttribute,因此请删除以下行:

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

关于c# - XmlIgnore 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5259720/

相关文章:

xml - XPath:找到具有条件的最后一个元素

c# - 为什么在 c# 中反序列化我的 packages.config 会返回空值?

jquery - 序列化不包括隐藏字段

c# - 在 WINRT 应用程序中使用转换器

c# - 如何创建谷歌联系人?

ios - Xcode 5 - 如何添加标题搜索路径和使用 GDataXMLNode

java - 无法将消息发送到远程对等本地类不兼容 : stream classdesc serialVersionUID

ios - 保存自定义 Objective-c 对象层次结构以实现持久性的最佳方法

c# - Entity Framework 上的 Razor 类验证

c# - 如何在thinktecture IdentityServer中禁用自动登录