Getting deserialized values - c#

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;
}
}

Related

how can i deserialize xml in 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

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;
}
}
}

Export a collection of objects (which in turn contains a collection object) to xml

I have a data object class which stores several properties. One is folder, and another is a string[] of all of the files in that array.
What I need to do is write this out to xml, like follows:
<X>
<a>dir</a>
<b>file</f>
So all of the files (there is a string[] array per data object), is nested below the directory field.
Is this easily possible? Or is there an external library which can do this easily for me?
Thanks
you mean something like this:
var myxml = new XElement(yourObj.FolderName);
myxml.Add(new XElement("Files",yourObj.Files.Select(x => new XElement("File",x)));
Use Xml Serializer to do the work for you?
using System.Linq;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System;
namespace NS
{
public class Data
{
public class Nested
{
public string The { get; set; }
public string[] stuff = {"lazy Cow Jumped Over", "The", "Moon"};
}
public List<Nested> Items;
}
static class Helper
{
public static string ToXml<T>(this T obj) where T:class, new()
{
if (null==obj) return null;
using (var mem = new MemoryStream())
{
var ser = new XmlSerializer(typeof(T));
ser.Serialize(mem, obj);
return System.Text.Encoding.UTF8.GetString(mem.ToArray());
}
}
public static T FromXml<T>(this string xml) where T: new()
{
using (var mem = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml)))
{
var ser = new XmlSerializer(typeof(T));
return (T) ser.Deserialize(mem);
}
}
}
class Program
{
public static void Main(string[] args)
{
var data = new Data { Items = new List<Data.Nested> { new Data.Nested {The="1"} } };
Console.WriteLine(data.ToXml());
var clone = data.ToXml().FromXml<Data>();
Console.WriteLine("Deserialized: {0}", !ReferenceEquals(data, clone));
Console.WriteLine("Identical: {0}", Equals(data.ToXml(), clone.ToXml()));
}
}
}
Will output
<?xml version="1.0" encoding="utf-8"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<Nested>
<stuff>
<string>lazy Cow Jumped Over</string>
<string>The</string>
<string>Moon</string>
</stuff>
<The>1</The>
</Nested>
</Items>
</Data>
Deserialized: True
Identical: True
There are some cornercases and gotchas especially when working with existing XSD, but this is all very well-trod and documented elsewhere.

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