I'm writing a Windows Store App and I need to store some data in Roaming Storage; for that I needed to serialize/deserialize some data. My serializer/deserializer functions are as below:
public string Serialize()
{
try
{
StringWriter sw = new StringWriter();
XmlSerializer xs = new XmlSerializer(typeof(RssData));
xs.Serialize(sw, this);
return sw.ToString();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
return String.Empty;
}
}
public void Deserialize(string serialized)
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(RssData));
XmlReader xr = XmlReader.Create(new StringReader(serialized));
RssData rd = xs.Deserialize(xr) as RssData;
this.categoryList = rd.categoryList;
this.defaultCategory = rd.defaultCategory;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
In summary, RssData has a list of RssCategory, and each RssCategory has a RssFeed. There is no problem with serialization and the following string is an example that I've produced using the Serialize function above:
<?xml version="1.0" encoding="utf-16"?>
<RssData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CategoryList>
<RssCategory>
<Name>No Category</Name>
<RssList>
<RssFeed>
<Title>HABERTURK.COM</Title>
<Url>http://www.haberturk.com/rss</Url>
<Image>http://www.haberturk.com/images/htklogo2.jpg</Image>
<Subtitle>HABERTÜRK - Türkiye'nin En Büyük İnternet Gazetesi</Subtitle>
</RssFeed>
</RssList>
</RssCategory>
</CategoryList>
</RssData>
However, when I Deserialize this XML, the resulting RssData has a CategoryList with 2 RssCategories, one is a RssCategory named "No Category" with an empty RssList, the other one is the correct one as defined in the XML; ie "No Category" with one RssFeed.
Is it a problem with my code or is XmlSerializer bugged?
Ok it seems that XmlSerializer first constructs the object using its no-parameter constructor then adds each item in the XML to the appropriate list. Thus if the constructor adds some items to that list, deserializing will result in a list that includes any item added in the constructor.
Edit: So if you serialize/deserialize a class that has a property of type Array/List/Container etc, in the no-parameter constructor you have to initialize it, but do not add anything to it.
试试看,告诉我:
Class c = new Class(); //class name of data which was serialized
using (var sr = new StringReader(Serialized data, wherever you are fetching it from)
{
var xs = new XmlSerializer(typeof(Class));
c= (Class)xs.Deserialize(sr);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.