-
July 10th, 2012, 05:21 AM
#1
XmlSerialization doesn't write to file
Hi,
I have been programming in Java for a few years and have just started learning C#.
I have created the following code:
Code:
public static void WriteToFile(Song song, String filename)
{
Console.WriteLine("About to write to file");
try
{
XmlSerializer writer = new XmlSerializer(typeof(Song));
StreamWriter file = new StreamWriter(filename);
writer.Serialize(file, song);
file.Close();
Console.WriteLine("Wrote to file successfully");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
But the resulting file only contains:
Code:
<?xml version="1.0" encoding="utf-8"?>
<Song xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
What am I doing wrong?
Thanks
-
July 11th, 2012, 03:57 AM
#2
Re: XmlSerialization doesn't write to file
Personally i'm using the TextWriter version
Code:
if (FileList.myFiles[0].Count > 0 && Global.bSerialEnable)
{
foreach (long key in FileList.myFiles[0].Keys)
{
tempdataitems.Add(new DataItem(key.ToString(), FileList.myFiles[0][key].ToString()));
}
XmlSerializer serializer = new XmlSerializer(typeof(List<DataItem>));
StringWriter sw = new StringWriter();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(sw, tempdataitems, ns);
string path = sMyPath + @"\data.bin";
File.WriteAllText(path, sw.ToString(), Encoding.Unicode);
sw.Dispose();
}
Where DataItem is this (only used for serialization)
Code:
public class DataItem
{
public string Key;
public string Value;
public DataItem(string key, string value)
{
Key = key;
Value = value;
}
public DataItem()
{
}
}
FileList is a personnal class. sMyPath is my application path
-
July 11th, 2012, 10:33 AM
#3
Re: XmlSerialization doesn't write to file
Managed to sort it out. Was due to my incorrect implementation of getters and setters, I think.
-
July 15th, 2012, 02:57 PM
#4
Re: XmlSerialization doesn't write to file
Originally Posted by dwally89
Managed to sort it out. Was due to my incorrect implementation of getters and setters, I think.
Most likely. Only properties with public setters and getters that are flagged with an xml attribute will get saved.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|