Files
win8phoneApp/CampusAppWP8/CampusAppWPortalLib8/Utility/XmlManager.cs
2013-10-15 13:13:09 +02:00

87 lines
3.4 KiB
C#

//-----------------------------------------------------------------------
// <copyright file="XmlManager.cs" company="BTU/IIT">
// The MIT License (MIT). Copyright (c) 2013 BTU/IIT.
// </copyright>
// <author>Stubbfel</author>
// <date>15.10.2013</date>
// <summary>Implements the XML manager class</summary>
//-----------------------------------------------------------------------
namespace CampusAppWPortalLib8.Utility
{
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;
/// <summary> Class provides some Xml-methods. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
public class XmlManager
{
/// <summary> Method deserialization a string to a Model. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <typeparam name="T"> the model. </typeparam>
/// <param name="xmlString"> the XmlString. </param>
/// <param name="validRootName"> name of the RootTag. </param>
/// <returns> return the deserialization of the model. </returns>
public static T DeserializationToModel<T>(string xmlString, string validRootName)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
XDocument document = XDocument.Parse(xmlString);
if (!document.Root.Name.ToString().Equals(validRootName))
{
XElement content = document.Root;
document = new XDocument();
document.Add(new XElement(validRootName, content));
}
T model = (T)serializer.Deserialize(document.CreateReader());
return model;
}
/// <summary> Deserialization a xml file to a model. </summary>
/// <remarks> Stubbfel, 20.08.2013. </remarks>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="xmlFilePath"> Path to the a XmlFile. </param>
/// <returns> model of the XmlFile. </returns>
public static T DeserializationFileToModel<T>(string xmlFilePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
XDocument document = XDocument.Load(xmlFilePath);
T model = (T)serializer.Deserialize(document.CreateReader());
return model;
}
/// <summary> Method serializes a model to a string. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <typeparam name="T"> type of the model. </typeparam>
/// <param name="model"> model object. </param>
/// <returns> serialized string. </returns>
public static string SerializationToString<T>(T model)
{
string retValue = string.Empty;
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(typeof(T));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, model, ns);
retValue = writer.ToString();
if (retValue.StartsWith("<?xml") == true)
{
int endTag = retValue.IndexOf("?>");
retValue = retValue.Substring(endTag + 2);
if (retValue.StartsWith("\r\n") == true)
{
retValue = retValue.Substring(2);
}
}
return retValue;
}
}
}