[英]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. 其中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; }
}
In some cases I want to ignore the value of value and I have this code 在某些情况下,我想忽略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);
but the value is still written in the output. 但该值仍写在输出中。
What am I doing wrong? 我究竟做错了什么?
If value is always ignored, you're better off assigning the attribute directly to the member. 如果始终忽略value,那么最好将属性直接分配给成员。
[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. 如果有条件地忽略了value,我怀疑您最好在序列化之前从根类中删除该元素。
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
. :D 再次更新:它应该是Items
而不是Item
,因为Value
在Items
。 Or if you like it the other way, it could be Value
in Item
and Item
all the way. 或者,如果您以其他方式喜欢它,则可能一直是Item
Value
和Item
Value
。
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 . 您应该传递属性名称而不是 文档中指定的xml名称 。
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: 同样按照Fun Mun Pieng的答案中的说明,您不应再添加XmlElementAttribute,因此请删除以下行:
attributes.XmlElements.Add(new XmlElementAttribute("Item"));
我相信应该使用XMLIgnore属性来装饰已经用XmlSerializable属性装饰的类的公共成员,那样可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.