2010-05-14 3 views
0

XML 직렬화에 대해 조사 중이며 많은 사전을 사용하고 있으므로이를 직렬화하고 싶습니다. 나는 그것을 위해 다음 해결책을 찾았다. (나는 그것을 자랑스럽게 생각한다! :)).사전의 제어 XML serialization <K, T>

<FooDictionary xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<Items> 
    <DictionaryItemOfInt32Foo> 
    <Key/> 
    <Value/> 
    </DictionaryItemOfInt32XmlProcess> 
<Items> 

이 나에게 좋은 솔루션을 제공하지만, : :이 클래스에서 파생

[XmlInclude(typeof(Foo))] 
public class XmlDictionary<TKey, TValue> 
{ 
    /// <summary> 
    /// Key/value pair. 
    /// </summary> 
    public struct DictionaryItem 
    { 
     /// <summary> 
     /// Dictionary item key. 
     /// </summary> 
     public TKey Key; 

     /// <summary> 
     /// Dictionary item value. 
     /// </summary> 
     public TValue Value; 
    } 

    /// <summary> 
    /// Dictionary items. 
    /// </summary> 
    public DictionaryItem[] Items 
    { 
     get { 
      List<DictionaryItem> items = new List<DictionaryItem>(ItemsDictionary.Count); 

      foreach (KeyValuePair<TKey, TValue> pair in ItemsDictionary) { 
       DictionaryItem item; 

       item.Key = pair.Key; 
       item.Value = pair.Value; 

       items.Add(item); 
      } 

      return (items.ToArray()); 
     } 
     set { 
      ItemsDictionary = new Dictionary<TKey,TValue>(); 

      foreach (DictionaryItem item in value) 
       ItemsDictionary.Add(item.Key, item.Value); 
     } 
    } 

    /// <summary> 
    /// Indexer base on dictionary key. 
    /// </summary> 
    /// <param name="key"></param> 
    /// <returns></returns> 
    public TValue this[TKey key] 
    { 
     get { 
      return (ItemsDictionary[key]); 
     } 
     set { 
      Debug.Assert(value != null); 
      ItemsDictionary[key] = value; 
     } 
    } 

    /// <summary> 
    /// Delegate for get key from a dictionary value. 
    /// </summary> 
    /// <param name="value"></param> 
    /// <returns></returns> 
    public delegate TKey GetItemKeyDelegate(TValue value); 

    /// <summary> 
    /// Add a range of values automatically determining the associated keys. 
    /// </summary> 
    /// <param name="values"></param> 
    /// <param name="keygen"></param> 
    public void AddRange(IEnumerable<TValue> values, GetItemKeyDelegate keygen) 
    { 
     foreach (TValue v in values) 
      ItemsDictionary.Add(keygen(v), v); 
    } 

    /// <summary> 
    /// Items dictionary. 
    /// </summary> 
    [XmlIgnore] 
    public Dictionary<TKey, TValue> ItemsDictionary = new Dictionary<TKey,TValue>(); 
} 

클래스는 다음과 같은 방법으로 직렬화

  • 은 어떻게 이름을 제어 할 수 있습니다 요소 DictionaryItemOfInt32Foo
  • Dictionary<FooInt32, Int32>을 정의하면 어떻게됩니까? FooFooInt32 클래스가 있습니까?
  • 위의 클래스를 최적화 할 수 있습니까?

대단히 감사합니다.

답변

0

클래스에 [XmlElement (ElementName = "name")]을 설정할 수 있습니다. 나는 이것을 시도하지 않았다, 당신은 어딘가에 그것을 설정해야 할 수도 있습니다. ElementName을 어딘가에 설정하는 것은 어쨌든 이동하는 길입니다.

+0

임의의 이름을 지정하면 요소를 deserialize 할 수 없습니다. – Luca