How to serialize to xml using Linq - c#

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

Related

Add dynamically xml tag to serialized object without modifying the object

I have an object serializable like this :
[XmlRoot("MyObject")]
[Serializable]
public class MyObject
{
public MyObject()
{
}
[XmlAttribute("name")]
public string Name { get; set; }
}
Right now I am able to export this object in an xml file with the following code :
public byte[] Export(MyObject myObject)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
byte[] value = null;
using (MemoryStream stream = new MemoryStream())
{
StreamWriter writer = new StreamWriter(stream);
serializer.Serialize(writer, myObject);
value = stream.ToArray();
}
return value;
}
For the moment, my exported xml is like this :
<MyObject Name="nameData">
I would like to export other data (a list of name related to myObject and obtained from another service) with this. But I cannot modify my MyObject class.
This is how I get the additionnal data :
public XElement GetExtraData(MyObject myObject)
{
List<string> datas = service.GetData(myObject);
var otherDatas = new XElement("otherDatas");
foreach (var data in datas)
{
var dataElement = new XElement("data");
var valueAttribute = new XAttribute("Value", data);
dataElement.Add(valueAttribute);
}
otherDatas.Add(dataElement);
}
I would like to append this otherDatas element to my previous element in order to obtain the following :
<MyObject Name="nameData">
<data Value="valueData">
<data Value="valueData">
<data Value="valueData">
But I don't see how, as this new method returns me a xElement created by me, and the natively .net serialization returns me an array of bytes.
Add the XElement returned from GetExtraData as Nodes to the original xml:
var doc = new XDocument(GetExtraData(new MyObject { Name = "someOtherName" }));
var byt = Export(new MyObject { Name = "nameData" });
using (var stream = new MemoryStream(byt))
{
var element = new XElement(XElement.Load(stream));
element.Add(doc.Nodes());
}
And save element

Why my serialized file has the word "ArrayOf" in it [duplicate]

I am serializing List of objects List<TestObject>
, and XmlSerializer generates <ArrayOfTestObject> attribute, I want rename it or remove it.
Can it be done with creating new class that encapsulated List as field?
[XmlRoot("Container")]
public class TestObject
{
public TestObject() { }
public string Str { get; set; }
}
List<TestObject> tmpList = new List<TestObject>();
TestObject TestObj = new TestObject();
TestObj.Str = "Test";
TestObject TestObj2 = new TestObject();
TestObj2.Str = "xcvxc";
tmpList.Add(TestObj);
tmpList.Add(TestObj2);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>));
using (XmlWriter writer = XmlWriter.Create(#"C:\test.xml", settings))
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
serializer.Serialize(writer, tmpList, namespaces);
}
<ArrayOfTestObject>
<TestObject>
<Str>Test</Str>
</TestObject>
<TestObject>
<Str>xcvxc</Str>
</TestObject>
</ArrayOfTestObject>
The most reliable way is to declare an outermost DTO class:
[XmlRoot("myOuterElement")]
public class MyOuterMessage {
[XmlElement("item")]
public List<TestObject> Items {get;set;}
}
and serialize that (i.e. put your list into another object).
You can avoid a wrapper class, but I wouldn't:
class Program
{
static void Main()
{
XmlSerializer ser = new XmlSerializer(typeof(List<Foo>),
new XmlRootAttribute("Flibble"));
List<Foo> foos = new List<Foo> {
new Foo {Bar = "abc"},
new Foo {Bar = "def"}
};
ser.Serialize(Console.Out, foos);
}
}
public class Foo
{
public string Bar { get; set; }
}
The problem with this is that when you use custom attributes you need to be very careful to store and re-use the serializer, otherwise you get lots of dynamic assemblies loaded into memory. This is avoided if you just use the XmlSerializer(Type) constructor, as it caches this internally automatically.
Change the following line from:
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>));
To:
XmlRootAttribute root = new XmlRootAttribute("TestObjects");
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>), root);
It should work.
You can add an additional parameter to the XmlSerializer constructor to essentially name the root element.
XmlSerializer xsSubmit = new XmlSerializer(typeof(List<DropDownOption>), new XmlRootAttribute("DropDownOptions"));
This would result in the following structure:
<DropDownOptions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DropDownOption>
<ID>1</ID>
<Description>foo</Description>
</DropDownOption>
<DropDownOption>
<ID>2</ID>
<Description>bar</Description>
</DropDownOption>
</DropDownOptions>
Create another class like :
[XmlRoot("TestObjects")]
public class TestObjects: List<TestObject>
{
}
Then apply below code while sealizing :
XmlSerializer serializer = new XmlSerializer(typeof(TestObjects));
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, tmpList);

C# XML Serialize object of Array object "There was an error generating the XML document."

I'm having a problem with the c# XML serialization system it's throws an Ambigus exception,
There was an error generating the XML document.
Now i have a Class that contains refferences to other classes and arrays of the other classes
E.G
namespace P2PFileLayout
{
public class p2pfile
{
public FileList FileList;
public StatusServer StatusServer;
public String Hash;
}
}
namespace P2PFileLayout.parts
{
public class StatusServer
{
public Auth Auth;
public Servers Servers;
}
public class Servers
{
public Server[] Server;
}
public class Server
{
public bool AuthRequired = false;
public string Address;
}
public class Files
{
public File[] File;
}
public class File
{
public string FileName = "";
public int BlockSize = 0;
public int BlockCount = 0;
}
public class Directory
{
public string Name;
public Files Files;
public Directory[] Dir;
}
public class Auth
{
public AuthServer[] AuthServer;
}
public class FileList
{
public Files Files;
public Directory[] Directory;
}
}
My Example data
// create the test file
testFile = new p2pfile();
// create a fake fileList
testFile.FileList = new P2PFileLayout.parts.FileList();
testFile.FileList.Directory = new P2PFileLayout.parts.Directory[1];
testFile.FileList.Directory[0] = new P2PFileLayout.parts.Directory();
testFile.FileList.Directory[0].Name = "testFolder";
testFile.FileList.Directory[0].Files = new P2PFileLayout.parts.Files();
testFile.FileList.Directory[0].Files.File = new P2PFileLayout.parts.File[2];
testFile.FileList.Directory[0].Files.File[0] = new P2PFileLayout.parts.File();
testFile.FileList.Directory[0].Files.File[0].FileName = "test.txt";
testFile.FileList.Directory[0].Files.File[0].BlockSize = 64;
testFile.FileList.Directory[0].Files.File[0].BlockCount = 1;
testFile.FileList.Directory[0].Files.File[1] = new P2PFileLayout.parts.File();
testFile.FileList.Directory[0].Files.File[1].FileName = "test2.txt";
testFile.FileList.Directory[0].Files.File[1].BlockSize = 64;
testFile.FileList.Directory[0].Files.File[1].BlockCount = 1;
// create a fake status server
testFile.StatusServer = new P2PFileLayout.parts.StatusServer();
testFile.StatusServer.Servers = new P2PFileLayout.parts.Servers();
testFile.StatusServer.Servers.Server = new P2PFileLayout.parts.Server[1];
testFile.StatusServer.Servers.Server[0] = new P2PFileLayout.parts.Server();
testFile.StatusServer.Servers.Server[0].Address = "http://localhost:8088/list.php";
// create a file hash (real)
HashGenerator.P2PHash hashGen = new HashGenerator.P2PHash();
testFile.Hash = hashGen.getHash();
treeView1.Nodes.Add(new TreeNode("Loading..."));
Classes.CreateTreeView ctv = new Classes.CreateTreeView();
ctv.BuildTreeView(testFile.FileList, treeView1);
treeView1.AfterCheck += new TreeViewEventHandler(treeView1_AfterCheck);
Now that is not as complicated as mine in terms of dept as my i loop objects so dir has support for more dirs but thats just an example
Then i'm serializing to a string var as i want to do a little more than just serialize it but here is my serialization
private string ToXml(object Obj, System.Type ObjType)
{
// instansiate the xml serializer object
XmlSerializer ser = new XmlSerializer(ObjType);
// create a memory stream for XMLTextWriter to use
MemoryStream memStream = new MemoryStream();
// create an XML writer using our memory stream
XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8);
// write the object though the XML serializer method using the W3C namespaces
ser.Serialize(xmlWriter, Obj);
// close the XMLWriter
xmlWriter.Close();
// close the memoryStream
memStream.Close();
// get the string from the memory Stream
string xml = Encoding.UTF8.GetString(memStream.GetBuffer());
// remove the stuff before the xml code we care about
xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
// clear any thing at the end of the elements we care about
xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
// return the XML string
return xml;
}
Can any one see why this is not working or any clues as to why it would not work normally
Why are you doing it manually?
What about this approach?
http://support.microsoft.com/kb/815813
Test test = new Test() { Test1 = "1", Test2 = "3" };
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(test.GetType());
MemoryStream ms = new MemoryStream();
x.Serialize(ms, test);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string xml = sr.ReadToEnd();
As for the ambigous message, take a look into the inner exceptions. XML serialization errors use innerexception a lot, and you usually have to look to all levels of InnerExceptions to know what is really happening.

How to rename <ArrayOf> XML attribute that generated after serializing List of objects

I am serializing List of objects List<TestObject>
, and XmlSerializer generates <ArrayOfTestObject> attribute, I want rename it or remove it.
Can it be done with creating new class that encapsulated List as field?
[XmlRoot("Container")]
public class TestObject
{
public TestObject() { }
public string Str { get; set; }
}
List<TestObject> tmpList = new List<TestObject>();
TestObject TestObj = new TestObject();
TestObj.Str = "Test";
TestObject TestObj2 = new TestObject();
TestObj2.Str = "xcvxc";
tmpList.Add(TestObj);
tmpList.Add(TestObj2);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>));
using (XmlWriter writer = XmlWriter.Create(#"C:\test.xml", settings))
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
serializer.Serialize(writer, tmpList, namespaces);
}
<ArrayOfTestObject>
<TestObject>
<Str>Test</Str>
</TestObject>
<TestObject>
<Str>xcvxc</Str>
</TestObject>
</ArrayOfTestObject>
The most reliable way is to declare an outermost DTO class:
[XmlRoot("myOuterElement")]
public class MyOuterMessage {
[XmlElement("item")]
public List<TestObject> Items {get;set;}
}
and serialize that (i.e. put your list into another object).
You can avoid a wrapper class, but I wouldn't:
class Program
{
static void Main()
{
XmlSerializer ser = new XmlSerializer(typeof(List<Foo>),
new XmlRootAttribute("Flibble"));
List<Foo> foos = new List<Foo> {
new Foo {Bar = "abc"},
new Foo {Bar = "def"}
};
ser.Serialize(Console.Out, foos);
}
}
public class Foo
{
public string Bar { get; set; }
}
The problem with this is that when you use custom attributes you need to be very careful to store and re-use the serializer, otherwise you get lots of dynamic assemblies loaded into memory. This is avoided if you just use the XmlSerializer(Type) constructor, as it caches this internally automatically.
Change the following line from:
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>));
To:
XmlRootAttribute root = new XmlRootAttribute("TestObjects");
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>), root);
It should work.
You can add an additional parameter to the XmlSerializer constructor to essentially name the root element.
XmlSerializer xsSubmit = new XmlSerializer(typeof(List<DropDownOption>), new XmlRootAttribute("DropDownOptions"));
This would result in the following structure:
<DropDownOptions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DropDownOption>
<ID>1</ID>
<Description>foo</Description>
</DropDownOption>
<DropDownOption>
<ID>2</ID>
<Description>bar</Description>
</DropDownOption>
</DropDownOptions>
Create another class like :
[XmlRoot("TestObjects")]
public class TestObjects: List<TestObject>
{
}
Then apply below code while sealizing :
XmlSerializer serializer = new XmlSerializer(typeof(TestObjects));
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, tmpList);

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