我有一个要序列化的对象,输出如下所示:
<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);但该值仍会写入输出中。
我做错了什么?
发布于 2011-03-10 22:30:20
现在你更新了你的问题,很明显你做错了什么。:)
[Serializable]
public class Item
{
[XmlElement("Value")]
public string DefaultValue { get; set; }
}应按照指定的in the documentation传递属性的名称,而不是xml名称。
overrides.Add(typeof(Item), "DefaultValue", attributes);..。而不是。
overrides.Add(typeof(Item), "Value", attributes);同样,正如Fun Mun Pieng的答案中所指定的,您不应该再添加XmlElementAttribute,因此删除以下行:
attributes.XmlElements.Add(new XmlElementAttribute("Item")); 发布于 2011-03-10 20:57:12
如果value总是被忽略,那么最好将属性直接赋值给成员。
[Serializable]
[XmlInclude(typeof(Item))]
public class Items
{
[XmlIgnore]
public string Value
}如果value被有条件地忽略,我怀疑您最好在序列化之前从根类中删除该元素。
至于你的代码,我怀疑(我可能错了,因为我还没有试过!)以下内容就足够了:
var overrides = new XmlAttributeOverrides();
var attributes = new XmlAttributes { XmlIgnore = true };
overrides.Add(typeof(Items), "Value", attributes);
serializer = new XmlSerializer(typeof(root), overrides);更新:我测试了上面的代码。它起作用了。:D 再次更新:它应该是Items而不是Item,因为Value在Items中。或者,如果你喜欢另一种方式,它可以是Item中的Value,也可以是Item。
发布于 2011-03-10 20:51:00
我认为应该用XMLIgnore属性来修饰用XmlSerializable属性修饰过的类的公共成员,这样才行得通。
https://stackoverflow.com/questions/5259720
复制相似问题