3

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; }
}
user829174
  • 6,132
  • 24
  • 75
  • 125
  • 1
    Something like this: [De/Serialize directly To/From XML Linq](http://stackoverflow.com/questions/314062/de-serialize-directly-to-from-xml-linq)? – Christofer Eliasson Feb 29 '12 at 15:51

6 Answers6

8

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();
jrummell
  • 42,637
  • 17
  • 112
  • 171
7

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.

Ocelot20
  • 10,510
  • 11
  • 55
  • 96
  • 1
    You aren't serializing with LINQ. LINQ is query language syntax. You are serializing/deserializing the result of a LINQ query. – jrummell Feb 29 '12 at 18:28
  • 2
    Semantics...the question states "How to serialize to xml *using* linq". Also, XElement and other LINQ-to-XML classes were purpose built so that they could be used directly with LINQ. – Ocelot20 Feb 29 '12 at 22:09
  • 2
    Not to mention that if you look at this users other question, he is clearly trying to do something using LINQ-to-XML: http://stackoverflow.com/questions/9485116/how-to-deserialize-xml-using-linq – Ocelot20 Mar 01 '12 at 13:58
1

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!
arazect
  • 13
  • 1
  • 3
1

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();
}
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
  • You actually don't need `[Serializable]` for `XmlSerializer`, but I think you do for binary serialization. – jrummell Feb 29 '12 at 15:55
  • you need to use it even if you are using XMLSerializer http://msdn.microsoft.com/en-us/library/system.serializableattribute(v=vs.100).aspx – Massimiliano Peluso Feb 29 '12 at 15:57
  • I find that hard to believe since the MSDN examples for `XmlSerializer` don't use it. – jrummell Feb 29 '12 at 15:59
  • Because it is the best way to serialize an instance of an object. Why do you need to implement something that is nicely done by the Framework? – Massimiliano Peluso Feb 29 '12 at 16:06
  • I agree, and it's probably the best thing to use in his case, but it's still not a true statement. – Ocelot20 Feb 29 '12 at 16:07
  • In software development there are always lots of way to get a result the matter is how you can get it with "less effort" keeping an eye on the performance and readability – Massimiliano Peluso Feb 29 '12 at 16:10
  • Again, I agree, but the statement "you have to use..." is not true. – Ocelot20 Feb 29 '12 at 16:34
  • what about the jrummell answer then? So you vote me down because I said "you have to" :-) – Massimiliano Peluso Feb 29 '12 at 16:43
  • you said "Note, this probably isn't the greatest approach, but it's answering the question at least." Here we don't just answer questions but we try to give the best solution possible for a giving context/question. In this scenario probably the user does not know about serialization that why we should point him to the right direction instead of "just answering" The question itself is not correct. – Massimiliano Peluso Feb 29 '12 at 16:57
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/8355/discussion-between-ocelot20-and-massimiliano-peluso) – Ocelot20 Feb 29 '12 at 17:47
  • @MassimilianoPeluso: not true. [Serializable] is meant for BINARY serialization. Check the example code in your provided link again. Meanwhile, the XmlSerializer documentation is completely clean of [Serializable]: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx – code4life Feb 29 '12 at 21:28
1

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);
Jon
  • 38,814
  • 81
  • 233
  • 382
0

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)
      )
    )
  )
);
Ral Zarek
  • 1,058
  • 4
  • 18
  • 25