gpt4 book ai didi

c# - XmlIgnore 不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 02:59:08 27 4
gpt4 key购买 nike

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

 <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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com