Serialize class to XML-file

using System.IO;
using System.Xml.Serialization;
XmlSerializer s = new XmlSerializer( typeof( ShoppingList ) );
TextWriter w = new StreamWriter( @"c:\list.xml" );
s.Serialize( w, mList );

Remark: you can also serialize to a string: use StringWriter instead of TextWriter

Deserialize XML-file to a (known) class

using System.Xml.Serialization;
XmlSerializer s = new XmlSerializer( typeof( ShoppingList ) );
StreamReader mStreamReader = new StreamReader("C:\List.xml");
ShoppingList mList = (ShoppingList)s.Deserialize(mStreamReader);

Example of class

public class ShoppingList
  public List<ShoppingItem> shoppingitemlist;
public class ShoppingItem
  public string Name;
  public string Number;
<ShoppingList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

Remark: the XML class can not contain a constructor. The serialization will not work then.
Remark: you have to use the List class (ShoppingList). It will compile attaching a List<> type to the xml serializer ( typeof( List<ShoppingItem> ), but this will give problems in run-time.

Deserialize XML-file to nodes

using System.Xml;

System.Xml.XmlDocument document = new XmlDataDocument();
foreach (XmlNode node in document.ChildNodes)
  if (node.Name != "xml")
    Log.Current.WriteLog(System.Diagnostics.TraceEventType.Information, string.Format("Document: <{0}>", node.Name));
    if (node.HasChildNodes)

A node has the properties .InnerXml, .InnerText and .FirstChild
.InnerXml shows the xml of the node. This means that '&amp;' will give '&amp;'
.InnerText shows the translated text of the node. This means that '&amp;' will give '&'
.FirstChild gives a lot more information. .FirstChild.Value gives the same value as .InnerText.

Serialize class to XML-message

System.Messaging.MessageQueue messageToBizTalk;
messageToBizTalk = new System.Messaging.MessageQueue(".\\Private$\\pelican");  // not local msq: "FORMATNAME:DIRECT=OS:dafehvw07674\Private$\pelican"
messageToBizTalk.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(Asset) });
MessageQueueTransaction messageQueueTransaction = new MessageQueueTransaction();
messageToBizTalk.Send(mAsset, messageQueueTransaction);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License