mitomed
mitomed

Reputation: 2066

Pass data to a view from an XML

I've been reading these days about deserialization, DOM, LINQ to XML and LINQ to XSD... for a while, but as I am a newbie I don't really get the whole picture so I'll try to explain you my scenery:

I fetch an xml from another's and I'm just trying to display the information that comes with it in an MVC project view.

I don't really have an xsd so I reckon for deserializing it into an object I'll have to use XSD tool for creating an scheme, then a class which matches this scheme and then populate this class and use it in a view. I think this can be done just with a sample xml, am I right?

Another option, is to create "my object" and populate it via DOM. I've done something similar lately (I posted a question about it) or even try some of the LINQ approaches (I've read the LINQ to XSD has been abandoned by Microsoft).

For the simple thing I'm trying to do I would go for the LINQ to XML but to be honest I haven't understand fully all the differences I've read about the advantages and disadvantages of the different approaches so if someone could help me to decide I really appreciate it.

Thanks in advance

Upvotes: 1

Views: 98

Answers (1)

Amadeus Hein
Amadeus Hein

Reputation: 716

I'll share the XMLManager we use in my current project. It's really easy to use, you just pass in the Type of the object you want to serialze to and from, like this:

YourObject myObject = new YourObject();
myObject.SomeInfoString = "Hello World";
XMLManager<YourObject>.SerialzeToFile(myObject, pathToSaveTo)

YourObject loadedObject = XMLManager<YourObject>.SerialzeFromFile(pathToYourFile)

Here's the implementation (please note you might want to do something in the catch-clauses, I've removed what we do there because it's specific to out implementation):

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;

/// <summary>
/// The XMLManager can be used to serialize to and from XML files.
/// </summary>
/// <typeparam name="T">The type to serialize.</typeparam>
public static class XmlManager<T>
{
    /// <summary>
    /// Static method SerializeFromFile
    /// </summary>
    /// <param name="path">
    /// The path.
    /// </param>
    /// <returns>
    /// returns T
    /// </returns>
    public static T SerializeFromFile(string path)
    {
        try
        {
            using (var xmlStream = new FileStream(path, FileMode.Open))
            {
                return FromStream(xmlStream);
            }
        }
        catch (Exception ex)
        {
            return default(T);
        }
    }

    /// <summary>
    /// Method FromStream
    /// </summary>
    /// <param name="xmlStream">
    /// The xml stream.
    /// </param>
    /// <returns>
    /// returns T
    /// </returns>
    public static T FromStream(Stream xmlStream)
    {
        try
        {
            var xmlReader = XmlReader.Create(xmlStream);
            var serializer = new XmlSerializer(typeof(T));

            var value = (T)serializer.Deserialize(xmlReader);
            return value;
        }
        catch (Exception ex)
        {
            return default(T);
        }
    }

    /// <summary>
    /// Method SerializeToFile
    /// </summary>
    /// <param name="xmlObject">
    /// The xml object.
    /// </param>
    /// <param name="xmlPath">
    /// The xml path.
    /// </param>
    /// <param name="overwriteExisting">
    /// The overwrite existing.
    /// </param>
    public static void SerializeToFile(T xmlObject, string xmlPath, bool overwriteExisting)
    {
        try
        {
            var mode = overwriteExisting ? FileMode.Create : FileMode.CreateNew;
            using (var xmlStream = new FileStream(xmlPath, mode))
            {
                ToStream(xmlObject, xmlStream);
            }
        }
        catch (Exception ex)
        {
        }
    }

    /// <summary>
    /// Method ToStream
    /// </summary>
    /// <param name="xmlObject">
    /// The xml object.
    /// </param>
    /// <param name="xmlStream">
    /// The xml stream.
    /// </param>
    public static void ToStream(T xmlObject, Stream xmlStream)
    {
        try
        {
            var xmlSettings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = false };

            var writer = XmlWriter.Create(xmlStream, xmlSettings);
            var serializer = new XmlSerializer(typeof(T));

            serializer.Serialize(writer, xmlObject);
        }
        catch (Exception ex)
        {
        }
    }
}

To pass this information to a view you make a property in the ViewModel of the object you've deserialized using the XMLManager, and bind it through XAML.

public string MyObjectInfoString 
{
    get
    {
        return this.myObject.InfoString;
    }

    set
    {
        if (this.myObject.InfoString == value)
        {
            return;
        }

        this.myObject.InfoString = value;
        RaisePropertyChanged("MyObjectInfoString");
    }
}

[Edit] Might as well show the XAML as well:

<TextBlock Text="{Binding MyObjectInfoString}" />

Upvotes: 1

Related Questions