2011-03-10 41 views
2

我有我試圖序列化對象,並且輸出看起來是這樣的:XmlIgnore不工作

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

,其中一項是類,類根用途。

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

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

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

在某些情況下,我想忽略的價值的價值,我有這樣的代碼

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

但該值仍寫在輸出。

我在做什麼錯?

+1

你可以添加Item類嗎? – 2011-03-10 13:05:07

+1

注意事項:在.NET中處理Xml序列化時,'[Serializable]'屬性沒有意義。 – Cheeso 2011-03-10 15:29:38

回答

2

現在你更新了你的問題,這顯然是你做錯了什麼。 :)

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

此外,在樂趣門Pieng的回答指定的,你不應該添加XmlElementAttribute了,所以刪除以下行:

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

是的,這是問題。我認爲這個班很明顯!這也意味着代碼的一些舊部分也是錯誤的。好極了 :/ – Marcom 2011-03-10 15:25:52

0

我相信XMLIgnore屬性應該用來裝飾一個已經用XmlSerializable屬性裝飾的類的公共成員,這種方式可以工作。

+0

但希望它在某些情況下被忽略,而不是所有的時間。 – Marcom 2011-03-10 12:51:41

2

如果值總是被忽略,那麼最好將屬性直接分配給成員。

[Serializable] 
[XmlInclude(typeof(Item))] 
public class Items 
{ 
    [XmlIgnore] 
    public string 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,因爲ValueItems。或者如果你喜歡它,可以使用ItemItem中的Value

+0

我只是想到了同樣的事情,這可能是解決方案。這確實會引發問題,當XmlElement已經被應用時該怎麼做,你怎麼去除它? – 2011-03-10 13:10:43

+0

....哦,我想它被刪除,因爲它只是取代所有的XML屬性... – 2011-03-10 13:13:48

+0

是的,我複製並粘貼了一個額外的線路作爲即時通訊嘗試不同的事情,但該劑量工作要麼:/ – Marcom 2011-03-10 13:27:20