how can i deserialize xml in C# - c#

My code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Threading.Tasks;
namespace PlaylistEditor.Writers
{
public class XMLPlaylistWriter : IPlaylistWriter
{
public void Save(Playlist ply, string filePath)
{
StreamWriter writer = null;
try
{
XmlSerializer xs = new XmlSerializer(ply.GetType());
writer = new StreamWriter(filePath);
xs.Serialize(writer, ply);
}
finally
{
if (writer != null)
writer.Close();
writer = null;
}
}
public Playlist Load(string filePath)
{
return null;
}
}
}
I wrote to load "return null;" i serialized that and ran code, but i can't do and find how to deserialize. thanks for your help.

You need to use XmlReader.
private Playlist Load(string filename)
{
Playlist playlist;
// Create an instance of the XmlSerializer specifying type and namespace.
var serializer = new
XmlSerializer(typeof(Playlist));
// A FileStream is needed to read the XML document.
using (var fs = new FileStream(filename, FileMode.Open))
{
using (var reader = XmlReader.Create(fs))
{
playlist = (Playlist) serializer.Deserialize(reader);
fs.Close();
}
}
return playlist;
}
reference from msdn => link

Related

Why can I no longer deserialize this data?

I am using the following code to serialize some data and save it to file:
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer((typeof(Item)));
Item item = ((Item)list.SelectedItems[0].Tag);
serializer.WriteObject(stream, item);
var filepath = Program.appDataPath + list.SelectedItems[0].Group.Name + ".group";
stream.Position = 0;
using (FileStream fileStream = new FileStream(filepath, FileMode.Create))
{
stream.WriteTo(fileStream);
}
And later on, I'm trying to read back that data from file and insert it into ListView:
private void OpenFiles()
{
// DEBUG ONLY:
// Read into memorystream and filestream.
Console.WriteLine("Attempeting to open note.");
bool canLoad = false;
foreach (string file in Directory.GetFiles(Program.appDataPath))
{
if (file.EndsWith(".group"))
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(
typeof(
List<Item>
)
);
using (FileStream fileStream =
new FileStream(
file,
FileMode.Open)
)
{
fileStream.CopyTo(stream);
}
stream.Position = 0;
//List<Withdrawal> tempWithList = new List<Withdrawal>();
foreach (Item item in (List<Item>)serializer.ReadObject(stream))
{
Console.WriteLine(item.Title + " " + item.Group.Name);
Item.Items.Add(item);
}
//Console.WriteLine("Got file \{file}");
//if (file.EndsWith(".group"))
//{
// Console.WriteLine("File is a group.");
// MemoryStream stream = new MemoryStream();
// DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Item>));
// using (FileStream fileStream = new FileStream(file, FileMode.Open))
// {
// fileStream.CopyTo(stream);
// }
// Console.WriteLine("Got stream");
// stream.Position = 0;
// try
// {
// Item.Items = (List<Item>)serializer.ReadObject(stream);
// Console.WriteLine("WTF?");
// }
// catch(Exception exception)
// {
// Console.WriteLine(exception.Message);
// }
// Console.WriteLine(Item.Items.Count);
// canLoad = true;
//}
//else Console.WriteLine("File is not a group.");
}
if (canLoad)
{
//list.Items.Clear();
foreach (Item item in Item.Items)
{
ListViewGroup group = new ListViewGroup(item.Group.Name);
list.Groups.Add(group);
list.Items.Add(
new ListViewItem(
item.Title,
group)
);
Console.WriteLine(item.Title + " " + item.Group.Name);
}
}
}
}
Now, the above exact code works in an older program (few months old), but it's not working in a new program. I have no idea why. I have set breakpoints EVERYWHERE and it has proven to be kind of pointless in this case.
One thing I did learn from setting a breakpoint is that even though the stream contains the data expected, the very next second, when it gets added to list, it is NULL. There is nothing in the list. I've run out of ideas, and Google wasn't of much help.
Group.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Notes
{
[DataContract]
public class Group
{
[DataMember]
public string Name { get; set; }
}
}
Item.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Notes
{
[DataContract]
[Serializable]
public class Item : Note
{
[DataMember]
public static List<Item> Items = new List<Item>();
[DataContract]
public enum ItemType
{
Group,
Note
}
[DataMember]
public ItemType Type { get; set; }
[DataMember]
public int Index { get; set; }
}
}
Note.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Notes
{
[DataContract]
public class Note
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Content { get; set; }
[DataMember]
public Group Group;
[DataContract]
public enum NoteImportance
{
Important,
Neutral,
NotImportant
}
[DataMember]
public NoteImportance Importance { get; set; }
[DataMember]
public bool Protected { get; set; }
}
}
How can I deserialize these objects/read from file and get them into a List or ListView? I've already done this, but for some reason it's not working anymore.
Any help would be appreciated.
When you create a .group file, you serialize a single Item:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Item));
// And later
serializer.WriteObject(stream, item);
But when you deserialize the contents of a .group file, you try to deserialize a List<Item>:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Item>));
// And later
foreach (Item item in (List<Item>)serializer.ReadObject(stream))
{
Item.Items.Add(item);
}
Those types don't match. But in order to deserialize the data you previously serialized, they need to match - or at least, the deserialized type cannot be a collection if the serialized type was, because collections are serialized as JSON arrays while other classes are serialized as JSON objects (name/value pairs).
Since it looks like each .group file has a single item, and there are many .group files in the directory you are scanning, you probably just want to do
var serializer = new DataContractJsonSerializer(typeof(Item));
// And later
var item = (Item)serializer.ReadObject(stream);
if (item != null)
Item.Items.Add(item);

Getting deserialized values

I have deserialized an xml file which contains a list of programs, days, times and a true or false value against them. The file looks similar to below.
<AlarmSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ProgramSettings>
<ProgramSetting>
<ProgramPathText>Alarm.exe</ProgramPathText>
<ProgramPathValue>D:\Documents\Work\Visual Studio\WindowsFormsApplication1\bin\Debug\Alarm.exe</ProgramPathValue>
<Monday>
<Time>11:08</Time>
<Enabled>true</Enabled>
</Monday>
<Tuesday>
<Time>17:08</Time>
<Enabled>true</Enabled>
</Tuesday>
</ProgramSetting>
</ProgramSettings>
</AlarmSettings>
I am trying to access the values but i keep getting stuck at the end of program settings where i cant see any methods that will be useful. I am needing to get to return the programpathtext values, programpathvalue values etc.
public void load()
{
AlarmSettings alarmSettings;
alarmSettings = AlarmSettings.Load(#"C:\Users\jason\Desktop\Booya.txt");
alarmSettings.ProgramSettings.
}
Any help would be appreciated. Thanks
AlarmSettings Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
namespace WindowsAlarm
{
public class AlarmSettings
{
public List<ProgramSetting> ProgramSettings = new List<ProgramSetting>();
public void Save(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(AlarmSettings));
TextWriter writer = new StreamWriter(filename);
serializer.Serialize(writer, this);
writer.Close();
}
public static AlarmSettings Load(string filename)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(AlarmSettings));
using (StreamReader reader = new StreamReader(filename))
{
AlarmSettings loadedSettings = (AlarmSettings)serializer.Deserialize(reader);
reader.Close();
return loadedSettings;
}
}
catch(Exception e)
{
throw e;
//return new AlarmSettings();
}
}
}
}
if you have proper object structure , make use of XmlSerializer
XmlSerializer serializer = new XmlSerializer(typeof(objecttype));
or make use of Linq to XML or create you own XML parser for that you can serach on google
you can also check post which talks about serialization : Object to XML using LINQ or XmlSerializer
I have solved the problem. the problem was that i was not going in and accessing the collection.
public void load()
{
AlarmSettings alarmSettings;
alarmSettings = AlarmSettings.Load(#"C:\Users\jason\Desktop\Booya.txt");
foreach (var setting in alarmSettings.ProgramSettings)
{
string pathtext = setting.ProgramPathText;
string pathvalue = setting.ProgramPathValue;
}
}

Xml & C# Deserialize Exception Error

I am working on a XNA gaming project and keep receiving the following error:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
Additional information: There is an error in XML document (2, 2).
This is my Xml code:
<?xml version="1.0" encoding="utf-8" ?>
<SplashScreen>
<Path>\SplashScreen\Game.png</Path>
</SplashScreen>
And this is my C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace WindowsGame3
{
public class Manager<T>
{
public Type Type;
public T Load(string Path)
{
T instance;
using (TextReader reader = new StreamReader(Path))
{
XmlSerializer xml = new XmlSerializer(Type);
instance = (T)xml.Deserialize(reader);
}
return instance;
}
public void save(string Path, object obj)
{
using (TextWriter writer = new StreamWriter(Path))
{
XmlSerializer xml = new XmlSerializer(Type);
xml.Serialize(writer, obj);
}
}
}
}
Here's the code that uses the above Manager class:
public void LoadContent(ContentManager Content)
{
this.Content = new ContentManager(Content.ServiceProvider, "Content");
GameScreenManager = new Manager<GameScreen>();
GameScreenManager.Type = currentScreen.Type;
currentScreen = GameScreenManager.Load("SplashScreen.xml");
currentScreen.LoadContent();
}
Did you check to see if the type T that you are calling the Load method on matches proper casing of the root element name SplashScreen ?

C# XML to Listbox Help

I have XML that is being returned back from a rest service WCF. The following is an example of the XML
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<catalog version="1.1"><dataset id="354" name="Mariano - Ship Drift" description="Global Currents, Static" datatype="currents" rank="5" saropsrank="4" format="netcdf" starttime="1980-01-01T00:00:00" endtime="2019-01-01T00:00:00" extentleft="-180.0000" extentbottom="-90.0000" extentright="180.0000" extenttop="90.0000" source="STATIC" wmslayeridstr="MARIANO_currents" confidence="L" directionfrom="no" image="ne_ndbc.jpg" />
</catalog>
</string>
I need to get the value from id, name, description, etc... and put it into a list or a listbox.
WebResponse response = restWebRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
Reponse stream is the stream that holds the XML.
Any ideas?
XDocument doc = XDocument.Load(responseStream);
var elem = doc.Descendants().FirstOrDefault(el => el.Name.LocalName == "dataset");
if(elem != null)
{
var attID = elem.Attribute("id");
if(attID != null)
Console.WriteLine(attID.Value);
}
OR
You could directly get the IEnumerable with an anonymous type:
XDocument doc = XDocument.Parse(xml);
var values = doc.Descendants("dataset")
.Select(el => new { id = el.Attribute("id").Value,
name = el.Attribute("name").Value
}
);
Here's another approach: (I tested your XML by loading it from a file.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
namespace delete4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load();
}
void Load()
{
var stream = new FileStream("c:\\pj\\data.txt", FileMode.Open);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "string";
xRoot.IsNullable = true;
xRoot.Namespace = "http://schemas.microsoft.com/2003/10/Serialization/";
XmlSerializer s = new XmlSerializer(typeof(sstring), xRoot);
var o = s.Deserialize(stream) as sstring; // o is your loaded object
stream.Close();
}
[ XmlRoot("string"), XmlType("string")]
public class sstring
{
public Catalog catalog;
}
public class Catalog
{
public Dataset dataset;
}
public class Dataset
{
[XmlAttribute("name")]
public string Name;
[XmlAttribute("id")]
public string ID;
[XmlAttribute("description")]
public string Description;
}
}
}

C# Error with XML Serialization "There is an error in XML document (2, 2)"

All, I am trying to serialize and de-serialize a class and the de-serialization is failing. There are tons of similar threads, but I am unable to resolve this. I am getting the following error "There is an error in XML document (2, 2)" Inner expection "{" was not expected."}"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace XMLSerialization
{
[System.Xml.Serialization.XmlRootAttribute(Namespace = "",
IsNullable = false)]
public class Level
{
private String _name;
private String _background;
public Level()
{
_name = "LEVEL_NAME";
_background = "LEVEL_BACKGROUND_IMAGE";
}
[XmlAttribute("LevelName")]
public String LevelName
{
get { return _name; }
set { _name = value; }
}
[XmlAttribute("Background")]
public String Background
{
get { return _background; }
set { _background = value; }
}
}
}
This is the code I use for de-serialization. The serialization is happening fine but the de-serialization is not going through. I think that I am doing a trivial mistake but I am unable to solve this!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace XMLSerialization
{
class Program
{
static void Main(string[] args)
{
Level oLevel1 = new Level();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(typeof(Level));
TextWriter textWriter = new StreamWriter("Level1.xml");
serializer.Serialize(textWriter, oLevel1, ns);
textWriter.Close();
Level oLevel2 = new Level();
XmlSerializer deserializer = new XmlSerializer(typeof(List<Level>));
TextReader textReader = new StreamReader("Level1.xml");
oLevel2 = (Level)deserializer.Deserialize(textReader);
textReader.Close();
}
}
}
I think you need to change the line
XmlSerializer deserializer = new XmlSerializer(typeof(List<Level>));
To
XmlSerializer deserializer = new XmlSerializer(typeof(Level));
You a serializing a Level and are trying to deserizalize a List<Level>.

Categories

Resources