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; i.e. "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.
Try this out and tell me:
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);
}
Related
I am running into the problem where I can't write serialized objects to a specific location in an XML document.
If I have an XML file that looks like:
<?xml version="1.0" encoding="utf-8"?>
<Spellements>
<MapSave />
</Spellements>
And I want to load my list of objects into the MapSave tag. How do I do it?
(the List of object type Node is passed in)
XmlSerializer ser = new XmlSerializer(typeof(List<Node>));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;
string fileName = Application.dataPath + "/Saves/Save" + GameVariables.saveFile + ".xml";
using (XmlWriter writer = XmlWriter.Create(File.Open(fileName, FileMode.Open), settings))
{
ser.Serialize(writer, list);
}
I have no problem serializing all the objects and writing them to the file. It works fine, but I seem to have no way to write it specifically as elements inside the area.
I have to use an XML writer to do Serialization, but there is no way to set the XML writer's "start writing here" location. As of now it just overwrites the whole document.
(I've done more then my fair share of research, I know how to set the writing location when using an XmlDocument, but not with XmlWriter -- Help please.
If you don't mind everytime writing the whole file you can do something like this:
[Serializable]
public class Spellement
{
public Spellement() { }
List<Node> mapSave = new List<Node>();
public List<Node> MapSave
{
get { return mapSave; }
set { mapSave = value; }
}
}
[Serializable]
public class Node
{
public Node() { }
public string Text { get; set; }
}
XmlSerializer xs = new XmlSerializer(typeof(Spellement));
using (XmlWriter st = XmlWriter.Create("C:\\test.xml"))
{
xs.Serialize(st, s);
}
I have a object which has a string property that has a value with double quotes in it. I need to serialize this object and then use that XML. I wont be deserializing this xml.
I am having trouble getting the right content in the XML file. Let me explain with a code sample:
[Serializable]
public class Test {
[XmlElement]
public string obj { get; set; }
}
class Program {
static void Main(string[] args) {
var st ="Priority == \"1\"";
Test test = new Test();
test.obj = st;
//Serialize this object
XmlSerializer xsSubmit = new XmlSerializer(typeof(Test));
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings {
OmitXmlDeclaration = true
});
var ns = new XmlSerializerNamespaces();//just to make things simpler here
ns.Add(string.Empty, string.Empty);
xsSubmit.Serialize(writer, test, ns);
//My XML
var xml = sww.ToString();
}
}
I need my xml to be:
<Test><obj>Priority=="1"</obj></Test>
I now get:
<Test><obj>Priority==\"1\"</obj></Test>
I even tried to encode the string into HTML using var html = HttpUtility.HtmlEncode(st);
In this case, the varible html is in the right format however on serializing I get:
<Test><obj>Priority=="1"</obj></Test>
Need some help please.
There was no issue with the code.
I actually get<Test><obj>Priority=="1"</obj></Test> and this is fine. The mistake I was making was that I was reading the value on the debugger. When I write it somewhere, the content was in the correct format.
The " didnt get converted to " because double quotes are as such accepted in an XML document. I can work with that in this case!
I have been using the traditional way of serializing content with the following code
private void SaveToXml(IdentifiableEntity IE)
{
try
{
XmlSerializer serializer = new XmlSerializer(IE.GetType());
TextWriter textWriter = new StreamWriter(IE.FilePath);
serializer.Serialize(textWriter, IE);
textWriter.Close();
}
catch (Exception e )
{
Console.WriteLine("erreur : "+ e);
}
}
private T LoadFromXml<T>(string path)
{
XmlSerializer deserializer = new XmlSerializer(typeof(T));
TextReader textReader = new StreamReader(path);
T entity = (T)deserializer.Deserialize(textReader);
textReader.Close();
return entity;
}
Though this approach does the trick, i find it a bit annoying that all my properties have to be public, that i need to tag the properties sometimes [XmlAttribute|XmlElement| XmlIgnore] and that it doesn't deal with dictionaries.
My question is : Is there a better way of serializing objects in c#, a way that with less hassle, more modern and easy to use?
First of all, I would suggest to use "using" blocks in your code.(Sample code)
If my understanding is OK, you are looking for a fast way to build your model classes that you will use during your deserialize/serialize operations.
Every Xml file is different and I don't know any generic way to serialize / deserialize them. At one moment you have to know if there will be an attribute, or elements or if any element can be null etc.
Assuming that you already have a sample XML file with a few lines which gives you general view of how it will look like
I would suggest to use xsd (miracle tool)
xsd yourXMLFileName.xml
xsd yourXMLFileName.xsd \classes
This tool will generate you every time model classes for the XML file you want to work it.
Than you serialize and deserialize easily
To deserialize (assuming that you'll get a class named XXXX representing root node in your xml)
XmlSerializer ser = new XmlSerializer(typeof(XXXX));
XXXX yourVariable;
using (XmlReader reader = XmlReader.Create(#"C:\yyyyyy\yyyyyy\YourXmlFile.xml"))
{
yourVariable= (XXXX) ser.Deserialize(reader);
}
To serialize
var serializer = new XmlSerializer(typeof(XXXX));
using(var writer = new StreamWriter(#"C:\yyyyyy\yyyyyy\YourXmlFile.xml"))
{
serializer.Serialize(writer, yourVariable);
}
I'm using XmlSerializer to serialize and then deserialize a simple object. When I deserialize the object to my surprise I find a child object was not properly deserialized but instead turned into XmlNode[].
Here is very nearly the structure I've got:
// This line I put in here as a way of sneaking into the XML the
// root node's C# namespace, since it's not the same as the
// deserializing code and the deserializing code seemed unable to
// deserialize properly without knowing the Type (see my code below).
// So I basically just use this fake construct to get the namespace
// and make a Type of it to feed the XmlSerializer() instantiation.
[XmlRoot(Namespace = "http://foo.com/CSharpNamespace/Foo.Bar")]
// This is because QueuedFile can be given to the Argument array.
[XmlInclude(typeof(QueuedFile))]
// This class is Foo.Bar.CommandAndArguments
public class CommandAndArguments {
public String Command;
public object[] Arguments;
}
// I don't think this matters to XmlSerialize, but just in case...
[Serializable()]
// I added this line just thinking maybe it would help, but it doesn't
// do anything. I tried it without the XmlType first, and that
// didn't work.
[XmlType("Foo.Baz.Bat.QueuedFile")]
// This class is Foo.Baz.Bat.QueuedFile (in a different c#
// namespace than CommandAndArguments and the deserializing code)
public QueuedFile {
public String FileName;
public String DirectoryName;
}
And the code which deserializes it looks like:
public static object DeserializeXml(String objectToDeserialize)
{
String rootNodeName = "";
String rootNodeNamespace = "";
using (XmlReader xmlReader = XmlReader.Create(new StringReader(objectToDeserialize)))
{
if (xmlReader.MoveToContent() == XmlNodeType.Element)
{
rootNodeName = xmlReader.Name;
rootNodeNamespace = xmlReader.NamespaceURI;
if (rootNodeNamespace.StartsWith("http://foo.com/CSharpNamespace/"))
{
rootNodeName = rootNodeNamespace.Substring("http://foo.com/CSharpNamespace/".Length) + "." +
rootNodeName;
}
}
}
//MessageBox.Show(rootNodeName);
try
{
Type t = DetermineTypeFromName(rootNodeName);
if (t == null)
{
throw new Exception("Could not determine type of serialized string. Type listed as: "+rootNodeName);
}
var s = new XmlSerializer(t);
return s.Deserialize(new StringReader(objectToDeserialize));
// object o = new object();
// MethodInfo castMethod = o.GetType().GetMethod("Cast").MakeGenericMethod(t);
// return castMethod.Invoke(null, new object[] { s.Deserialize(new StringReader(objectToDeserialize)) });
}
catch (InvalidOperationException)
{
return null;
}
}
And here is the XML when the CommandAndArguments is serialized:
<?xml version="1.0" encoding="utf-16"?>
<CommandAndArguments xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://foo.com/CSharpNamespace/Foo.Bar">
<Command>I am a command</Command>
<Arguments>
<anyType xsi:type="Foo.Baz.Bat.QueuedFile">
<FileName xmlns="">HelloWorld.txt</FileName>
<DirectoryName xmlns="">C:\foo\bar</DirectoryName>
</anyType>
</Arguments>
</CommandAndArguments>
But when I deserialize I am given a CommandAndArguments object where Arguments is XmlNode[] with the first item being the attribute giving the QueuedFile as the type and the other indices being elements of the properties. But why wasn't the QueuedFile object recreated?
I suspect this might somehow have do with C# namespaces and the engine doing the deserializing not being able to find or work with QueuedFile... But I don't see why since when I forgot the XmlInclude() it made sure to tell me it didn't expect QueuedFile and now that I've added the XmlInclude() I get no error, just an incomplete deserialization.
Help? I've read everything I can find to read and Googled everything I know to Google and am stuck. I certainly have a lot to learn about XML serialization but I'm not sure how I'm failing at something which should be pretty simple (I actually did something almost exactly like this before without any problem, the only difference then was that everything was in the same C# namespace).
Are you able to change the XML format or is it fixed? I don't know what the problem you are having is, but I use the DataContractSerializer classes extensively with no problems.
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
public static void WriteObject(string fileName)
{
Console.WriteLine(
"Creating a Person object and serializing it.");
Person p1 = new Person("Zighetti", "Barbara", 101);
FileStream writer = new FileStream(fileName, FileMode.Create);
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
writer.Close();
}
public static void ReadObject(string fileName)
{
Console.WriteLine("Deserializing an instance of the object.");
FileStream fs = new FileStream(fileName,
FileMode.Open);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person deserializedPerson =
(Person)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
Console.WriteLine(String.Format("{0} {1}, ID: {2}",
deserializedPerson.FirstName, deserializedPerson.LastName,
deserializedPerson.ID));
}
To anyone coming along with a similar problem, depending on your situation you're probably better off with NetDataContractSerializer. It is an alternative to DataContractSerializer which records the .Net types in the XML making deserialization a breeze, since it knows exactly what types are involved and thus you do not need to tell it what type the root object is with the deserialize command. And it can produce output in XML or binary form (I prefer XML for easier debugging).
Here is some sample code for easily serializing and deserializing an object to and from a string:
private static object Deserialize(string xml)
{
object toReturn = null;
using (Stream stream = new MemoryStream())
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
stream.Write(data, 0, data.Length);
stream.Position = 0;
var netDataContractSerializer = new NetDataContractSerializer();
toReturn = netDataContractSerializer.Deserialize(stream);
}
return toReturn;
}
private static string Serialize(object obj)
{
using (var memoryStream = new MemoryStream())
using (var reader = new StreamReader(memoryStream))
{
var netDataContractSerializer = new NetDataContractSerializer();
netDataContractSerializer.Serialize(memoryStream, obj);
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}
Easy as pie!
I have a generic list of objects that I am trying to serialize/desearilize.
The objects' class itself has a property of a generic list of another class,
class Exercise
{
public int Duration { get; set; };
public string Name { get; set; };
}
class Session
{
public DateTime Date { get; set; }
public List<Exercise> ExerciseList { get; set; }
}
This is how serialization looks like
Session session = new Session((DateTime)dpDate.Value, exercises); //exercises is a List<Exercise>
...
Sessions = new List<Session>();
Sessions.Add(session);
XmlSerializer xml = new XmlSerializer(typeof(List<Session>));
xml.Serialize(stream, Sessions);
...
This is how the resulting xml looks like
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfSession xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Session>
<Date>2012-01-17T00:00:00+03:00</Date>
<ExerciseList>
<Exercise>
<Name>q</Name>
<Duration>10</Duration>
</Exercise>
<Exercise>
<Name>w</Name>
<Duration>20</Duration>
</Exercise>
</ExerciseList>
</Session>
</ArrayOfSession>
However, when trying to deserialize it like so
...
XmlSerializer xml = new XmlSerializer(typeof(List<Session>));
Sessions = (List<Session>)xml.Deserialize(stream);
...
It shows the following error on the second line :
InvalidOperationException There is an error in xml document (3,4)
So what might be the problem?
EDIT:
I need to clarify that it is for windows phone, so the stream is formed like this
IsolatedStorageFileStream stream = storage.CreateFile(fileName);
Sessions = new List<Session>();
Sessions.Add(session);
XmlSerializer xml = new XmlSerializer(typeof(List<Session>));
xml.Serialize(stream, Sessions);
However, for the purpose of showing the xml structure I used
StringWriter s = new StringWriter();
xml.Serialize(s, Sessions);
So, I do not have access to the actual xml file to remove encoding="utf-16"
It won't let me answer my own question due to low reputation for another 5 hours, so I'll post it here:
So, the problem turned out to be not in encoding, as has been suggested.
Apparently, all the classes that are being serialized must have a default parameter less constructor present. Now that I've added them everything works splendidly. (I still do not know if it is a thing with windows phone xml serialization or xml serialization in general)
Try this
//Serialize
public static string SerializeObject<T>(object o)
{
MemoryStream ms = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF32);
xs.Serialize(xtw, o);
ms = (MemoryStream)xtw.BaseStream;
UTF32Encoding encoding = new UTF32Encoding();
return encoding.GetString(ms.ToArray());
}
//Deserialize
public static T DeserializeObject<T>(string xml)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
UTF32Encoding encoding = new UTF32Encoding();
Byte[] byteArray = encoding.GetBytes(xml);
MemoryStream ms = new MemoryStream(byteArray);
XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF32);
return (T)xs.Deserialize(ms);
}
Hope this solves your problem.
If possible go through this post.
You're missing a closing tag for the <ArrayOfSession> element.
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfSession xmlns:xsi= ...">
<Session>
...
</Session>
</ArrayOfSession>