2009-12-30 75 views
2

我有一個類,我需要做一些自定義的XML輸出,因此我實現了IXmlSerializable接口。但是,我想用默認序列化輸出一些字段,但我想更改xml標記名稱。當我調用serializer.Serialize時,我得到了XML中的默認標籤名稱。我可以改變這些嗎?自定義序列化使用XmlSerializer

這裏是我的代碼:

public class myClass: IXmlSerializable 
{ 
    //Some fields here that I do the custom serializing on 
    ... 

    // These fields I want the default serialization on except for tag names 
    public string[] BatchId { get; set; } 
    ... 

    ... ReadXml and GetSchema methods are here ... 

    public void WriteXml(XmlWriter writer) 
    {       
     XmlSerializer serializer = new XmlSerializer(typeof(string[])); 
     serializer.Serialize(writer, BatchId); 
     ... same for the other fields ... 

     // This method does my custom xml stuff 
     writeCustomXml(writer); 
    } 

    // My custom xml method is here and works fine 
    ... 
} 

這裏是我的XML輸出:

<MyClass> 
    <ArrayOfString> 
     <string>2643-15-17</string> 
     <string>2642-15-17</string> 
     ... 
    </ArrayOfString> 
    ... My custom Xml that is correct .. 
    </MyClass> 

我想直到結束是:

<MyClass> 
    <BatchId> 
     <id>2643-15-17</id> 
     <id>2642-15-17</id> 
     ... 
    </BatchId> 
    ... My custom Xml that is correct .. 
    </MyClass> 
+0

多久你序列化/反序列化?在應用生命週期內或僅在啓動/關閉期間執行100次。如果前者我有一個更靈活的實現。 – 2009-12-30 20:30:59

+0

真的只有序列化一次。這個應用程序是一個簡單的工具,它從專有數據庫格式中提取數據並保存到xml。所以我將數據拉入對象模型,然後立即序列化。大部分數據很簡單,所以我不需要實現IXmlSerializable ...但是這個特定的數據有點痛苦。 – KrisTrip 2009-12-30 20:34:50

+0

看看這裏,代碼是MIT http://code.google.com/p/videobrowser/source/browse/MediaBrowser/Library/Persistance/XmlSettings.cs還有一個單元測試,你可能不得不擴展一下,但所有的架構都在那裏。加上你的場景,它會比XmlSerializer更好地執行 – 2009-12-30 20:41:23

回答

7

在很多情況下,你可以使用XmlSerializer構造函數重載接受XmlAttributeOverrides指定此額外的名字信息(例如,通過一個新的XmlRootAttribute) - 但是,這並不對數組工作AFAIK。我期望string[]的例子,只是手動編寫它會更簡單。在大多數情況下,IXmlSerializable是很多額外的工作 - 我儘可能避免這樣的原因。抱歉。

+0

XmlSerializer是一種老舊的無用的低效技術,應該在MS之前被MS棄用,或者在最低限度重新實現。我只是遇到了麻煩。更好的使用協議緩衝區:p – 2009-12-30 20:29:39

+0

看看我是否可以將pb-net的輸出轉換爲xml; -p – 2009-12-30 20:41:46

+0

你應該完全做到這一點,並使其可以插入,以便人們可以實現自己的持久性格式,然後你甚至可以使用sqlite作爲數據存儲... – 2009-12-30 20:48:58

3

你可以標記您的領域屬性爲control the serialized XML。例如,添加以下屬性:

[XmlArray("BatchId")] 
[XmlArrayItem("id")] 
public string[] BatchId { get; set; } 

可能會讓你那裏。

+1

試過了。沒有運氣。 – KrisTrip 2009-12-30 20:12:57

0

如果有人仍然在尋找這個,你可以肯定地使用XmlArrayItem,但是這需要是一個類中的一個屬性。

爲便於閱讀,您應該使用同一個詞的複數和單數。

/// <summary> 
    /// Gets or sets the groups to which the computer is a member. 
    /// </summary> 
    [XmlArrayItem("Group")] 
    public SerializableStringCollection Groups 
    { 
     get { return _Groups; } 
     set { _Groups = value; } 
    } 
    private SerializableStringCollection _Groups = new SerializableStringCollection(); 



<Groups> 
    <Group>Test</Group> 
    <Group>Test2</Group> 
</Groups> 

大衛