将数据传递到XML中的视图

时间:2012-04-27 07:23:28

标签: c# xml dom linq-to-xml deserialization

这些天我一直在阅读关于反序列化,DOM,LINQ to XML和LINQ to XSD ......一段时间了,但由于我是新手,我并没有真正全面了解所以我会尝试向你解释我的风景:

我从另一个人那里获取一个xml,我只是想在MVC项目视图中显示它附带的信息。

我真的没有xsd所以我认为将它反序列化为一个对象我将不得不使用XSD工具来创建一个方案,然后是一个匹配这个方案的类,然后填充这个类并在一个类中使用它视图。我想这可以用xml样本完成,我是对的吗?

另一种选择是创建“我的对象”并通过DOM填充它。我最近做了类似的事情(我发布了一个关于它的问题)或甚至尝试了一些LINQ方法(我已经读过LINQ to XSD已经被微软抛弃了)。

对于我想要做的简单事情,我会选择LINQ to XML,但说实话,我还没有完全理解我所读到的关于不同方法的优点和缺点的所有差异,所以如果有人可以帮我决定我真的很感激。

提前致谢

1 个答案:

答案 0 :(得分:1)

我将分享我们在当前项目中使用的XMLManager。它非常易于使用,您只需传入要串行化的对象的类型,如下所示:

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

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

以下是实现(请注意,您可能希望在catch子句中执行某些操作,我已删除了我们在那里执行的操作,因为它特定于实现):

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)
        {
        }
    }
}

要将此信息传递给视图,您需要在使用XMLManager反序列化的对象的ViewModel中创建一个属性,并通过XAML绑定它。

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

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

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

[编辑]也可以显示XAML:

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