Serialize an object to XElement and Deserialize it in memory - c#

I want to serialize an object to XML, but I don't want to save it on the disk. I want to hold it in a XElement variable (for using with LINQ), and then Deserialize back to my object.
How can I do this?

You can use these two extension methods to serialize and deserialize between XElement and your objects.
public static XElement ToXElement<T>(this object obj)
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
}
public static T FromXElement<T>(this XElement xElement)
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(xElement.CreateReader());
}
USAGE
XElement element = myClass.ToXElement<MyClass>();
var newMyClass = element.FromXElement<MyClass>();

You can use XMLSerialization
XML serialization is the process of converting an object's public
properties and fields to a serial format (in this case, XML) for
storage or transport. Deserialization re-creates the object in its
original state from the XML output. You can think of serialization as
a way of saving the state of an object into a stream or buffer. For
example, ASP.NET uses the XmlSerializer class to encode XML Web
service messages
and XDocument Represents an XML document to achieve this
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace ConsoleApplication5
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
XmlSerializer xs = new XmlSerializer(typeof(Person));
Person p = new Person();
p.Age = 35;
p.Name = "Arnold";
Console.WriteLine("\n Before serializing...\n");
Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age,p.Name));
XDocument d = new XDocument();
using (XmlWriter xw = d.CreateWriter())
xs.Serialize(xw, p);
// you can use LINQ on elm now
XElement elm = d.Root;
Console.WriteLine("\n From XElement...\n");
elm.Elements().All(e => { Console.WriteLine(string.Format("element name {0} , element value {1}", e.Name, e.Value)); return true; });
//deserialize back to object
Person pDeserialized = xs.Deserialize((d.CreateReader())) as Person;
Console.WriteLine("\n After deserializing...\n");
Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age, p.Name));
Console.ReadLine();
}
}
}
and here is output

(Late answer)
Serialize:
var doc = new XDocument();
var xmlSerializer = new XmlSerializer(typeof(MyClass));
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, obj);
}
// now you can use `doc`(XDocument) or `doc.Root` (XElement)
Deserialize:
MyClass obj;
using(var reader = doc.CreateReader())
{
obj = (MyClass)xmlSerializer.Deserialize(reader);
}

ToXelement without Code Analysis issues, same answer as Abdul Munim but fixed the CA issues (except for CA1004, this cannot be resolved in this case and is by design)
public static XElement ToXElement<T>(this object value)
{
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
memoryStream = null;
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, value);
return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
finally
{
if (memoryStream != null)
{
memoryStream.Dispose();
}
}
}

What about
public static byte[] BinarySerialize(Object obj)
{
byte[] serializedObject;
MemoryStream ms = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
try
{
b.Serialize(ms, obj);
ms.Seek(0, 0);
serializedObject = ms.ToArray();
ms.Close();
return serializedObject;
}
catch
{
throw new SerializationException("Failed to serialize. Reason: ");
}
}

Related

How to serialize different objects to the same XML file and then deserialize

When a user uses my program, it will generate many thousands of objects over the course of a couple of hours. These cannot accumulate in RAM, so I want to write them to a single file as they are generated. Then, in a different program, the objects must all be deserialized.
When I try to serialize different objects of the same class to the same XML file and then try to deserialize later, I get:
System.InvalidOperationException: 'There is an error in XML document (1, 206).'
Inner Exception
XmlException: There are multiple root elements. Line 1, position 206.
Here is an example of a .NET 6.0 console app that recapitulates this problem:
using System.Xml.Serialization;
using System.IO;
using System.Xml;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
// Serialize a person
using (FileStream stream = new FileStream("people.xml", FileMode.Create))
{
Person jacob = new Person { Name = "Jacob", Age = 33, Alive = true };
XmlSerializer serializer = new XmlSerializer(typeof(Person));
serializer.Serialize(stream, jacob);
}
// Serialize another person to the same file using the "clean XML" method
// https://stackoverflow.com/questions/1772004/how-can-i-make-the-xmlserializer-only-serialize-plain-xml
using (StreamWriter stream = new StreamWriter("people.xml", true))
{
Person rebecca = new Person { Name = "Rebecca", Age = 45, Alive = true };
stream.Write(SerializeToString(rebecca));
}
// Deserialize the people
List<Person> people = new List<Person>();
using (FileStream stream = new FileStream("people.xml", FileMode.Open))
{
XmlSerializer deserializer = new XmlSerializer(typeof(Person));
while (stream.Position < stream.Length)
{
people.Add((Person)deserializer.Deserialize(stream));
}
}
// See the people
foreach (Person person in people)
Console.WriteLine($"Hello. I am {person.Name}. I am {person.Age} and it is {person.Alive} that I am alive.");
}
// Serialize To Clean XML
public static string SerializeToString<T>(T value)
{
var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(value.GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, value, emptyNamespaces);
return stream.ToString();
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool Alive { get; set; }
public Person()
{
Name = "";
}
}
}
Probably not the perfect answer, but could you de-serialize to a list, append your new person, and then re-serialize?
public static List<Person> ReadPeople(string file)
{
var people = new List<Person>();
if (File.Exists(file))
{
var serializer = new XmlSerializer(typeof(List<Person>));
using (var stream = new FileStream(file, FileMode.Open))
{
people = (List<Person>)serializer.Deserialize(stream);
}
}
return people;
}
public static void SavePerson(string file, Person person)
{
var people = ReadPeople(file);
people.Add(person);
var serializer = new XmlSerializer(typeof(List<Person>));
using (var stream = new FileStream(file, FileMode.Create))
{
serializer.Serialize(stream, people);
}
}
Additionally, on the "FileMode.Create", is the "FileMode.Append" option. The problem with that is it will append lists next to each other, rather than nesting the "people"
NB - I've split this into two functions to give the flexibility of being able to load the file easily

Generic Interface for deserializing and returning XML objects [duplicate]

When using XML serialization in C#, I use code like this:
public MyObject LoadData()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));
using (TextReader reader = new StreamReader(settingsFileName))
{
return (MyObject)xmlSerializer.Deserialize(reader);
}
}
(and similar code for deserialization).
It requires casting and is not really nice. Is there a way, directly in .NET Framework, to use generics with serialization? That is to say to write something like:
public MyObject LoadData()
{
// Generics here.
XmlSerializer<MyObject> xmlSerializer = new XmlSerializer();
using (TextReader reader = new StreamReader(settingsFileName))
{
// No casts nevermore.
return xmlSerializer.Deserialize(reader);
}
}
An addition to #Oded, you can make the method Generic aswell:
public T ConvertXml<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(xml));
}
This way you don't need to make the whole class generic and you can use it like this:
var result = ConvertXml<MyObject>(source);
Make your serialization class/method generic:
public T LoadData<T>()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(settingsFileName))
{
return (T)xmlSerializer.Deserialize(reader);
}
}
A simple generic wrapper:
public class GenericSerializer<T> : XmlSerializer
{
public GenericSerializer(): base(typeof(T)) { }
}
This will serialize your object to the bin/debug folder:
static void Main(string[] args)
{
Person p = new Person { Name = "HelloWorld" };
GenericSerializer<Person> ser = new GenericSerializer<Person>();
ser.Serialize(new StreamWriter("person.xml"), p);
}
Try this.
public class SerializeConfig<T> where T : class
{
public static void Serialize(string path, T type)
{
var serializer = new XmlSerializer(type.GetType());
using (var writer = new FileStream(path, FileMode.Create))
{
serializer.Serialize(writer, type);
}
}
public static T DeSerialize(string path)
{
T type;
var serializer = new XmlSerializer(typeof(T));
using (var reader = XmlReader.Create(path))
{
type = serializer.Deserialize(reader) as T;
}
return type;
}
}
always work's for me
public static string ObjectToXmlSerialize<T>(T dataToSerialize)
{
try
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringwriter, dataToSerialize);
return stringwriter.ToString();
}
catch (Exception ex)
{
}
return null;
}
and this is for Deserialize:
public static T XmlDeserializeToObject<T>(string xmlText)
{
try
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
catch (Exception ex)
{
}
return default(T);
}

How to serialize to xml using Linq

How can i serialize Instance of College to XML using Linq?
class College
{
public string Name { get; set; }
public string Address { get; set; }
public List<Person> Persons { get; set; }
}
class Person
{
public string Gender { get; set; }
public string City { get; set; }
}
You can't serialize with LINQ. You can use XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(College));
// Create a FileStream to write with.
Stream writer = new FileStream(filename, FileMode.Create);
// Serialize the object, and close the TextWriter
serializer.Serialize(writer, i);
writer.Close();
Not sure why people are saying you can't serialize/deserialize with LINQ. Custom serialization is still serialization:
public static College Deserialize(XElement collegeXML)
{
return new College()
{
Name = (string)collegeXML.Element("Name"),
Address = (string)collegeXML.Element("Address"),
Persons = (from personXML in collegeXML.Element("Persons").Elements("Person")
select Person.Deserialize(personXML)).ToList()
}
}
public static XElement Serialize(College college)
{
return new XElement("College",
new XElement("Name", college.Name),
new XElement("Address", college.Address)
new XElement("Persons", (from p in college.Persons
select Person.Serialize(p)).ToList()));
);
Note, this probably isn't the greatest approach, but it's answering the question at least.
You can't use LINQ. Look at the below code as an example.
// This is the test class we want to
// serialize:
[Serializable()]
public class TestClass
{
private string someString;
public string SomeString
{
get { return someString; }
set { someString = value; }
}
private List<string> settings = new List<string>();
public List<string> Settings
{
get { return settings; }
set { settings = value; }
}
// These will be ignored
[NonSerialized()]
private int willBeIgnored1 = 1;
private int willBeIgnored2 = 1;
}
// Example code
// This example requires:
// using System.Xml.Serialization;
// using System.IO;
// Create a new instance of the test class
TestClass TestObj = new TestClass();
// Set some dummy values
TestObj.SomeString = "foo";
TestObj.Settings.Add("A");
TestObj.Settings.Add("B");
TestObj.Settings.Add("C");
#region Save the object
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass));
// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(#"C:\test.xml");
SerializerObj.Serialize(WriteFileStream, TestObj);
// Cleanup
WriteFileStream.Close();
#endregion
/*
The test.xml file will look like this:
<?xml version="1.0"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SomeString>foo</SomeString>
<Settings>
<string>A</string>
<string>B</string>
<string>C</string>
</Settings>
</TestClass>
*/
#region Load the object
// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(#"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
// Load the object saved above by using the Deserialize function
TestClass LoadedObj = (TestClass)SerializerObj.Deserialize(ReadFileStream);
// Cleanup
ReadFileStream.Close();
#endregion
// Test the new loaded object:
MessageBox.Show(LoadedObj.SomeString);
foreach (string Setting in LoadedObj.Settings)
MessageBox.Show(Setting);
you have to use the XML serialization
static public void SerializeToXML(College college)
{
XmlSerializer serializer = new XmlSerializer(typeof(college));
TextWriter textWriter = new StreamWriter(#"C:\college.xml");
serializer.Serialize(textWriter, college);
textWriter.Close();
}
You can use that if you needed XDocument object after serialization
DataClass dc = new DataClass();
XmlSerializer x = new XmlSerializer(typeof(DataClass));
MemoryStream ms = new MemoryStream();
x.Serialize(ms, dc);
ms.Seek(0, 0);
XDocument xDocument = XDocument.Load(ms); // Here it is!
I'm not sure if that is what you want, but to make an XML-Document out of this:
College coll = ...
XDocument doc = new XDocument(
new XElement("College",
new XElement("Name", coll.Name),
new XElement("Address", coll.Address),
new XElement("Persons", coll.Persons.Select(p =>
new XElement("Person",
new XElement("Gender", p.Gender),
new XElement("City", p.City)
)
)
)
);

Model to XML file mapping - How to find location of deserialized object in soucre XML File.

Which is the best way to map my model to XML file using c# serializer. I mean that if for example I select an deserialized object I could be able to find the xml source text in XML file.
I got a working sample for you and you can explore further on it.
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication5
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public int XMLLine { get; set; }
}
public class Persons : List<Person> { }
class Program
{
static void Main(string[] args)
{
//create your objects
Person p = new Person();
p.Age = 35;
p.Name = "Arnold";
Person p2 = new Person();
p2.Age = 36;
p2.Name = "Tom";
Persons ps = new Persons();
ps.Add(p);
ps.Add(p2);
//Serialize them to XML
XmlSerializer xs = new XmlSerializer(typeof(Persons));
XDocument d = new XDocument();
using (XmlWriter xw = d.CreateWriter())
xs.Serialize(xw, ps);
//print xml
//System.Diagnostics.Debug.WriteLine(d.ToString());
// it will produce following xml. You can save it to file.
//I have saved it to variable xml for demo
string xml = #"<ArrayOfPerson>
<Person>
<Age>35</Age>
<Name>Arnold</Name>
<XMLLine>0</XMLLine>
</Person>
<Person>
<Age>36</Age>
<Name>Tom</Name>
<XMLLine>0</XMLLine>
</Person>
</ArrayOfPerson>";
XDocument xdoc = XDocument.Parse(xml, LoadOptions.SetLineInfo);
// A little trick to get xml line
xdoc.Descendants("Person").All(a => { a.SetElementValue("XMLLine", ((IXmlLineInfo)a).HasLineInfo() ? ((IXmlLineInfo)a).LineNumber : -1); return true; });
//deserialize back to object
Persons pplz = xs.Deserialize((xdoc.CreateReader())) as Persons;
pplz.All(a => { Console.WriteLine(string.Format("Name {0} ,Age{1} ,Line number of object in XML File {2}", a.Name, a.Age, a.XMLLine)); return true; });
Console.ReadLine();
}
}
}
and It will give your results like
Name Arnold ,Age35 ,Line number of object in XML File 2
Name Tom ,Age36 ,Line number of object in XML File 7
You can try this extension method:
public static string ToXml<T>(this object obj)
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
return Encoding.ASCII.GetString(memoryStream.ToArray());
}
}
}
public static void ToXmlFile<T>(this object obj, string fileName)
{
using (TextWriter streamWriter = new StreamWriter(fileName))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
}
}
USAGE:
// you will get this on a string variable
var xmlString = yourModel.ToXml<YourModel>();
// you will save our object in a file.
yourModel.ToXmlFile<YourModel>(#"C:\yourModelDump.xml");
Please be noted to add SerializableAttribute on your class
[Serializable]
public class YourModel
{
//...
}
This should do it

C# - Deserialize a List<String>

I can serialize a list really easy:
List<String> fieldsToNotCopy =new List<String> {"Iteration Path","Iteration ID"};
fieldsToNotCopy.SerializeObject("FieldsToNotMove.xml");
Now I need a method like this:
List<String> loadedList = new List<String();
loadedList.DeserializeObject("FieldsToNotMove.xml");
Is there such a method? Or am I going to need to create an XML reader and load it in that way?
EDIT: Turns out there is no built in SerialzeObject. I had made one earlier in my project and forgot about it. When I found it I thought it was built in. In case you are curious this is the SerializeObject that I made:
// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
TextWriter textWriter = new StreamWriter(filename);
xmlSerializer.Serialize(textWriter, toSerialize);
textWriter.Close();
}
There is no such builtin method as SerializeObject but it's not terribly difficult to code one up.
public void SerializeObject(this List<string> list, string fileName) {
var serializer = new XmlSerializer(typeof(List<string>));
using ( var stream = File.OpenWrite(fileName)) {
serializer.Serialize(stream, list);
}
}
And Deserialize
public void Deserialize(this List<string> list, string fileName) {
var serializer = new XmlSerializer(typeof(List<string>));
using ( var stream = File.OpenRead(fileName) ){
var other = (List<string>)(serializer.Deserialize(stream));
list.Clear();
list.AddRange(other);
}
}
These are my serialize/deserialize extension methods that work quite well
public static class SerializationExtensions
{
public static XElement Serialize(this object source)
{
try
{
var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
var xdoc = new XDocument();
using (var writer = xdoc.CreateWriter())
{
serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
}
return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
}
catch (Exception x)
{
return new XElement("Error", x.ToString());
}
}
public static T Deserialize<T>(this XElement source) where T : class
{
try
{
var serializer = XmlSerializerFactory.GetSerializerFor(typeof(T));
return (T)serializer.Deserialize(source.CreateReader());
}
catch //(Exception x)
{
return null;
}
}
}
public static class XmlSerializerFactory
{
private static Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();
public static XmlSerializer GetSerializerFor(Type typeOfT)
{
if (!serializers.ContainsKey(typeOfT))
{
System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));
var newSerializer = new XmlSerializer(typeOfT);
serializers.Add(typeOfT, newSerializer);
}
return serializers[typeOfT];
}
}
You just need to define a type for your list and use it instead
public class StringList : List<String> { }
Oh, and you don't NEED the XmlSerializerFactory, it's just there since creating a serializer is slow, and if you use the same one over and over this speeds up your app.
I'm not sure whether this will help you but I have dome something which I believe to be similar to you.
//A list that holds my data
private List<Location> locationCollection = new List<Location>();
public bool Load()
{
//For debug purposes
Console.WriteLine("Loading Data");
XmlSerializer serializer = new XmlSerializer(typeof(List<Location>));
FileStream fs = new FileStream("CurrencyData.xml", FileMode.Open);
locationCollection = (List<Location>)serializer.Deserialize(fs);
fs.Close();
Console.WriteLine("Data Loaded");
return true;
}
This allows me to deserialise all my data back into a List<> but i'd advise putting it in a try - catch block for safety. In fact just looking at this now is going to make me rewrite this in a "using" block too.
I hope this helps.
EDIT:
Apologies, just noticed you're trying to do it a different way but i'll leave my answer there anyway.
I was getting error while deserializing to object. The error was "There is an error in XML document (0, 0)". I have modified the Deserialize function originally written by #JaredPar to resolve this error. It may be useful to someone:
public static void Deserialize(this List<string> list, string fileName)
{
XmlRootAttribute xmlRoot = new XmlRootAttribute();
xmlRoot.ElementName = "YourRootElementName";
xmlRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(List<string>), xmlRoot);
using (var stream = File.OpenRead(fileName))
{
var other = (List<string>)(serializer.Deserialize(stream));
list.Clear();
list.AddRange(other);
}
}
Create a list of products be serialized
List<string> Products = new List<string>
{
new string("Product 1"),
new string("Product 2"),
new string("Product 3"),
new string("Product 4")
};
Serialization
using (FileStream fs = new FileStream(#"C:\products.txt", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, Products);
}
Deserialization
using (FileStream fs = new FileStream(#"C:\products.txt", FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
var productList = (List<string>)bf.Deserialize(fs);
}

Categories

Resources