繁体   English   中英

使用字典将xml反序列化为对象

[英]Deserializing xml to object with dictionary

这是我的课程结构:

class DataItem
{
   public string Id { get; set; }
   public string Type { get; set; }

   private Dictionary<string, DataProperty> properties = new Dictionary<string, DataProperty>();

   public Dictionary<string, DataProperty> Properties
   {
       get { return properties; }
       set { properties = value; }
   }
}

public class DataProperty
{    
      public string Key { get; set; }
      public string Value { get; set; }
      public bool Required { get; set; }
}

这是我要使用的XML( 注:如果需要,我可以更改xml ):

<Data>
  <DataItem>
    <id>ph15</id>
    <type>core</type>
    <properties>
      <DataProperty>
        <key>size</key>
        <value>50%</value>
        <required>false</required>
      </DataProperty>
      <DataProperty>
        <key>color</key>
        <value>red</value>
        <required>true</required>
      </DataProperty>
    </properties>
  </DataItem>
  <DataItem>
    <id>ph234</id>
    <type>core</type>
    <properties>
    </properties>
  </DataItem>
</Data>

最终,XML应该加载到另一个字典中:

private Dictionary<string, DataItem> Mydata;

不幸的是,通用词典无法xml序列化。

解决方法是创建一个单独的字段,专门用于支持序列化,该序列化将字典的元素公开为键/值对的列表。 然后,您还必须使用XmlIgnore属性标记字典成员。

另外,您可以使用XmlSerializer之外的其他东西(例如DataContractSerializer )来支持字典类型。

这里是文章链接 ,提供了一个很好的示例,说明了如何修改类型以支持带字典的XML序列化。

如果使用此代码,则有一点很重要-序列化的项目可能会以任意顺序出现在输出中。 这是因为使用专断词(无序)作为数据的存储模型的结果。

[XmlIgnore()]   
public Dictionary<string, DataProperty> Properties
{   
    set { properties = value; }   
    get { return properties ; }   
}


[XmlArray("Stuff")]   
[XmlArrayItem("StuffLine", Type=typeof(DictionaryEntry))]   
public DictionaryEntry[] PropertiesList
{   
    get  
    {   
        //Make an array of DictionaryEntries to return   
        DictionaryEntry[] ret=new DictionaryEntry[Properties.Count];   
        int i=0;   
        DictionaryEntry de;   
        //Iterate through Stuff to load items into the array.   
        foreach (KeyValuePair<string, DataProperty> props in Properties)   
        {   
            de = new DictionaryEntry();   
            de.Key = props.Key;   
            de.Value = props.Value;   
            ret[i]=de;   
            i++;   
        }   
        return ret;   
    }   
    set  
    {   
        Properties.Clear();   
        for (int i=0; i<value.Length; i++)   
        {   
            Properties.Add((string)value[i].Key, (DataProperty)value[i].Value);   
        }   
    }   
}  

我知道以前已经回答过这个问题,但是由于我有一种非常简洁的方式(代码)来使用DataContractSerializer类(由WCF使用,但是可以并且应该在任何地方使用)进行IDictionary序列化,所以我不能拒绝在这里提供它:

public static class SerializationExtensions
{
    public static string Serialize<T>(this T obj)
    {
        var serializer = new DataContractSerializer(obj.GetType());
        using (var writer = new StringWriter())
        using (var stm = new XmlTextWriter(writer))
        {
            serializer.WriteObject(stm, obj);
            return writer.ToString();
        }
    }
    public static T Deserialize<T>(this string serialized)
    {
        var serializer = new DataContractSerializer(typeof(T));
        using (var reader = new StringReader(serialized))
        using (var stm = new XmlTextReader(reader))
        {
            return (T)serializer.ReadObject(stm);
        }
    }
}

尽管我尚未对其进行测试,但它在.NET 4中可以完美运行,并且在.NET 3.5中也可以运行。 我将流式传输到字符串是因为它对我来说更方便,尽管我可以将较低级别的序列化引入Stream,然后用它来序列化为字符串,但是我倾向于只在需要时进行泛化(就像过早的优化是邪恶的一样) ,这是过早的概括...)

用法很简单:

// dictionary to serialize to string
Dictionary<string, object> myDict = new Dictionary<string, object>();
// add items to the dictionary...
myDict.Add(...);
// serialization is straight-forward
string serialized = myDict.Serialize();
...
// deserialization is just as simple
Dictionary<string, object> myDictCopy = 
    serialized.Deserialize<Dictionary<string,object>>();

myDictCopy将是myDict的逐字记录副本。

您还将注意到,提供的通用方法将能够序列化任何类型(据我所知),因为它不仅限于IDictionary接口,它实际上可以是任何通用类型T。

希望它可以帮助某个人!

我建议您使用DataContractSerializer。 它确实支持字典。

但是,另一种方法是创建一个具有Value和Key属性的简单对象。 然后使用List(Of thatObject),它应该可以工作。 但这取决于您是否只想传输值键数据,导致字典中一部分的所有其他方法均不可用。

简短的答案: 你不能

这是因为即使您可以想象序列化方案,.NET序列化程序也不能保证重新序列化的键将具有相同的哈希值。

长答案: 可以,但这需要很多工作

为您提供的解决方案是对整个对象进行手动序列化,或用一个简单的Wrapper属性(将IDictionary包裹起来,但将其公开为成对列表)替换Dictionary。 (您可以稍后将其转换。)

但是 :与上面的问题相同,您不能保证重新序列化的密钥将具有与序列化之前相同的哈希码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM