How to serialize and deserialize an object in C# to a XML file

The following code shows how to serialize and deserialize an object in C# to a XML file.

 

Code

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
namespace MobileUI.BC
{
public class SerializationHelper<T> where T : class, new()
{
private string _fileName;
public string FileName
{
get
{
if (string.IsNullOrEmpty(_fileName))
{
_fileName = "Data.xml";
}
return _fileName;
}
set
{
_fileName = value;
}
}
private T _data;
public T Data
{
get
{
if (_data == null)
{
_data = new T();
}
return _data;
}
set
{
_data = value;
}
}
public void Save()
{
string filePath = Path.Combine(GetExecutionPath(), FileName);
using (TextWriter writer = new StreamWriter(filePath))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
xs.Serialize(writer, this.Data);
}
}
public T Load()
{
string filePath = Path.Combine(GetExecutionPath(), FileName);
using (TextReader reader = new StreamReader(filePath))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
this.Data = xs.Deserialize(reader) as T;
}
return this.Data;
}
public static string GetExecutionPath()
{
string codeBase = Assembly.GetExecutingAssembly().GetName().CodeBase;
return new Uri(Path.GetDirectoryName(codeBase)).LocalPath;
}
}
}

 

Example

        [TestMethod]
public void SaveTest()
{
Data data = new Data();
data.Days = 2;
SerializationHelper<Data> sh = new SerializationHelper<Data>();
sh.Data = data;
sh.Save();
data.Days = 3;
data = sh.Load();
Console.WriteLine(data.Days);
}

 

Result

2

Dynamically call a xslt template

You cannot call a xslt template like:

<xsl:variable name="templateName" select="test"></xsl:variable>
<xsl:call-template name="$templateName">

<xsl:template name="test">
</xsl:template>


The clossed you can get to calling a xslt template dynamically is to use the <xsl:if or <xsl:choose based on a variable:

<xsl:if test="$parameter1=$templateName">
  <xsl:call-template name="test">
</xsl:if>

How to copy XML nodes between documents (use ImportNode)

http://www.geekpedia.com/tutorial150_How-to-copy-XML-nodes-between-documents.html

To copy node between XmlDocuments use importnode:
// Store the root node of the destination document into an XmlNode
// The 1 in ChildNodes[1] is the index of the node to be copied (where 0 is the first node)
XmlNode rootDest = myDestDoc["DestinationRoot"];
// Store the node to be copied into an XmlNode
XmlNode nodeOrig = mySourceDoc["SourceRoot"].ChildNodes[1];
// Store the copy of the original node into an XmlNode
XmlNode nodeDest = myDestDoc.ImportNode(nodeOrig, true);
// Append the node being copied to the root of the destination document
rootDest.AppendChild(nodeDest);

You should use System.Security.SecurityElement.Escape in C# to escape special characters in XML and not System.Web.HttpUtility.HtmlEncode

You should use the function System.Security.SecurityElement.Escape and not the function System.Web.HttpUtility.HtmlEncode to escape special characters in XML if you don’t want the characters like éûÉ to be converted to &#233;&#251;&#201; which is permit able but not necessary en can result in long xml fields.

var escapedXml = System.Security.SecurityElement.Escape(@"&<>'""’éûÉغ");
Console.WriteLine(escapedXml);
// Result=&amp;&lt;&gt;&apos;&quot;’éûÉغ
escapedXml = System.Web.HttpUtility.HtmlEncode(@"&<>'""’éûÉغ");
Console.WriteLine(escapedXml);
// Result=&amp;&lt;&gt;'&quot;’&#233;&#251;&#201;غ

To revert the escape process, use:

SecurityElement securityElement = System.Security.SecurityElement.FromString("<test>H&amp;M</test>");
string unescapedText = securityElement.Text;
Console.WriteLine(unescapedText); // Result: H&M

Or

// Data is the un-escaped text that should be inserted in a XML tag.
string data = "H&amp;M";
// A xml tag with the name "test" is used, just for creating the SecurityElement.
var securityElement = new SecurityElement("test", data);
// Generate the un-escaped text.
string unescapedText = securityElement.Text;
// Result: H&M
Console.WriteLine(unescapedText);

Or use the InnerText property of a XmlNode:

// Data is the un-escaped text that should be inserted in a XML tag.
string data = "H&amp;M";
XmlDocument document = new XmlDocument();
document.LoadXml(string.Format("<test>{0}</test>", data));
XmlNode node = document.DocumentElement.FirstChild;
// Generate the un-escaped text.
string unescapedText = node.InnerText;
// Result: H&M
Console.WriteLine(unescapedText);

SketchPath XPath query tool

If you want to know the XPath query to an element of a XML file, but you’re new to XPath, you can use the Freeware tool: SketchPath to get show the XPath query. In mine case I wanted to update the “ConnectionString” property of a SSIS pacakge.

XPath query to use in NANT Task: /DTS:Executable/DTS:Configuration[1]/DTS:Property[2]

 image

You can download SketchPath at: http://pgfearo.googlepages.com/downloads