XML

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 );
w.Close();

Reference
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);
mStreamReader.Close();

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">
  <shoppingitemlist>
    <ShoppingItem>
      <Name>ee</Name>
      <Number>3</Number>
    </ShoppingItem>
    <ShoppingItem>
      <Name>ff</Name>
      <Number>2</Number>
    </ShoppingItem>
  </shoppingitemlist>
</ShoppingList>

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();
document.Load(path);
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)
      Createdocument(node);
  }
}

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();
messageQueueTransaction.Begin();
messageToBizTalk.Send(mAsset, messageQueueTransaction);
messageQueueTransaction.Commit();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License