89 lines
3.2 KiB
C#
89 lines
3.2 KiB
C#
//-----------------------------------------------------------------------
|
|
// <copyright file="XmlManager.cs" company="BTU/IIT">
|
|
// Company copyright tag.
|
|
// </copyright>
|
|
// <author>stubbfel</author>
|
|
// <sience>18.06.2013</sience>
|
|
//----------------------------------------------------------------------
|
|
namespace CampusAppWPortalLib8.Utility
|
|
{
|
|
using System.IO;
|
|
using System.Xml.Linq;
|
|
using System.Xml.Serialization;
|
|
|
|
/// <summary>
|
|
/// Class provides some Xml-methods
|
|
/// </summary>
|
|
public class XmlManager
|
|
{
|
|
/// <summary>
|
|
/// Method deserialization a string to a Model
|
|
/// </summary>
|
|
/// <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>
|
|
/// <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;
|
|
}
|
|
}
|
|
}
|