问:我使用http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx中的可序列化字典类来序列化字典。这很好用,但我遇到了一个恼人的问题。
<System.Xml.Serialization.XmlRoot("DataBase")> _
Public Class cDataBase
<System.Xml.Serialization.XmlNamespaceDeclarations()> _
Public ns As New System.Xml.Serialization.XmlSerializerNamespaces()
<System.Xml.Serialization.XmlElement("Tables")> _
Public Tables1 As New SerializableDictionary(Of String, cTable)
End Class ' cDataBase当我序列化上述类的实例时,创建的xml如下所示:
<Tables>
<item>
<key>
<string>MyTable</string>
</key>
<value>
<Table CreationDate="0001-01-01T00:00:00" LastModified="0001-01-01T00:00:00">
<Columns>
<Column Name="PrimaryKeyName">
<DataType>Uniqueidentifier</DataType>
<Length>36</Length>
</Column>
</Columns>
<Rows>
<Row>
<Item>Reihe1</Item>
<Item>Reihe2</Item>
<Item>Reihe3</Item>
</Row>
<Row>
<Item>Reihe1</Item>
<Item>Reihe2</Item>
<Item>Reihe3</Item>
</Row>如果我能弄清楚如何将键从重命名为属性中定义的内容,那就太好了
<key>
<string>MyTable</string>
</key>基本上类似于XmlArrayItem属性,例如下面,如果(仅)字典是一个数组...
<System.Xml.Serialization.XmlArray("Tables")> _
<System.Xml.Serialization.XmlArrayItem("Table")> _
Public Tables As New List(Of cTable)我想尝试将string更改为一个从String继承的自定义类,我可以为其提供一个名称,但问题是,一个人不能从string继承...
发布于 2010-07-28 20:34:40
如果我没看错您的问题,您想要将序列化输出从下面的代码更改为:
<Tables>
<item>
<key>
<string>MyTable</string>
</key>
<value>
<!-- snip -->
</value>
</item>
</Tables>类似这样的东西:
<Tables>
<item>
<key>
<TableId>MyTable</TableId>
</key>
<value>
<!-- snip -->
</value>
</item>
</Tables>您还提到可以实现这一点的一种方法是创建您自己的类型,该类型继承自System.String,正如您还提到的那样,这显然是不可能的,因为它是sealed。
但是,您可以通过将键值封装在您自己的类型中,然后使用XmlTextAttribute控制XmlSerializer输出(请参阅MSDN)来实现相同的结果:
默认情况下,XmlSerializer将类成员序列化为
元素。但是,如果将XmlTextAttribute应用于成员,则XmlSerializer会将其值转换为XML文本。这意味着该值被编码到XML元素的内容中。
在您的示例中,您将按如下方式使用该属性:
public class TableId
{
[XmlText]
public string Name
{
get;
set;
}
}然后使用此类型作为Dictionary的密钥。它应该能达到你想要的效果。
发布于 2010-07-16 19:26:29
您可以专门化Dictionary模板,也可以从专门化派生出您想要的序列化。
发布于 2010-07-30 13:44:39
虽然这可能有点离题,但我需要问一问为什么要使用XML来序列化它?如果您只是想保存对象状态以备将来使用,我建议使用JSON而不是XML。
一个很大的好处是您可以轻松地保存一个普通的Dictionary类,而不必编写任何特殊的代码。有效负载也比JSON小得多,所以如果需要的话,它是一种很好的通过网络发送的格式。
Scott Gu有一些关于使用JavascriptSerializer here的信息。我建议将其作为object的扩展方法。然后你可以这样做:
Dictionary<int, string> myDict = new Dictionary<int,string>();
myDict.Add(10,"something");
string jsonData = myDict.ToJSON();如果你对此感兴趣,请让我知道,我可以发布我使用的扩展方法的代码。(sry不在工作,我也没带在这儿。)
https://stackoverflow.com/questions/3264181
复制相似问题