将对象序列化为XElement并在内存中反序列化它

时间:2011-12-04 05:43:45

标签: c# xml linq serialization c#-4.0

我想将对象序列化为XML,但我不想将其保存在磁盘上。我想将它保存在XElement变量中(用于LINQ),然后反序列化回我的对象​​。

我该怎么做?

5 个答案:

答案 0 :(得分:92)

您可以使用这两种扩展方法在XElement和对象之间进行序列化和反序列化。

public static XElement ToXElement<T>(this object obj)
{
    using (var memoryStream = new MemoryStream())
    {
        using (TextWriter streamWriter = new StreamWriter(memoryStream))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            xmlSerializer.Serialize(streamWriter, obj);
            return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
        }
    }
}

public static T FromXElement<T>(this XElement xElement)
{
        var xmlSerializer = new XmlSerializer(typeof(T));
        return (T)xmlSerializer.Deserialize(xElement.CreateReader());
}

<强> USAGE

XElement element = myClass.ToXElement<MyClass>();
var newMyClass = element.FromXElement<MyClass>();

答案 1 :(得分:23)

您可以使用XMLSerialization

  

XML序列化是转换对象公共的过程   属性和字段为串行格式(在本例中为XML)   储存或运输。 反序列化会在其中重新创建对象   XML输出的原始状态。您可以将序列化视为   一种将对象状态保存到流或缓冲区中的方法。对于   例如,ASP.NET使用XmlSerializer类对XML Web进行编码   服务信息

XDocument Represents an XML document实现此目标

   using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;


namespace ConsoleApplication5
{
  public class Person
  {
    public int Age { get; set; }
    public string Name { get; set; }
  }

  class Program
  {
    static void Main(string[] args)
    {

      XmlSerializer xs = new XmlSerializer(typeof(Person));

      Person p = new Person();
      p.Age = 35;
      p.Name = "Arnold";

      Console.WriteLine("\n Before serializing...\n");
      Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age,p.Name));

      XDocument d = new XDocument();
      using (XmlWriter xw = d.CreateWriter())
        xs.Serialize(xw, p);

      // you can use LINQ on elm now

      XElement elm = d.Root;

      Console.WriteLine("\n From XElement...\n");

      elm.Elements().All(e => { Console.WriteLine(string.Format("element name {0} , element value {1}", e.Name, e.Value)); return true; });

      //deserialize back to object
      Person pDeserialized = xs.Deserialize((d.CreateReader())) as Person;

      Console.WriteLine("\n After deserializing...\n");
      Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age, p.Name));

      Console.ReadLine();

    }
  }


}

这里输出enter image description here

答案 2 :(得分:12)

(迟到的答案)

序列化:

var doc = new XDocument();
var xmlSerializer = new XmlSerializer(typeof(MyClass));
using (var writer = doc.CreateWriter())
{
    xmlSerializer.Serialize(writer, obj);
}
// now you can use `doc`(XDocument) or `doc.Root` (XElement)

反序列化:

MyClass obj; 
using(var reader = doc.CreateReader())
{
    obj = (MyClass)xmlSerializer.Deserialize(reader);
}

答案 3 :(得分:0)

没有代码分析问题的ToXelement,与Abdul Munim相同的答案,但修复了CA问题(CA1004除外,在这种情况下无法解决,并且是设计)

    public static XElement ToXElement<T>(this object value)
    {
        MemoryStream memoryStream = null;
        try
        {
            memoryStream = new MemoryStream();
            using (TextWriter streamWriter = new StreamWriter(memoryStream))
            {
                memoryStream = null;
                var xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(streamWriter, value);
                return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
            }
        }
        finally
        {
            if (memoryStream != null)
            {
                memoryStream.Dispose();
            }
        }
    }

答案 4 :(得分:-1)

怎么样?
public static byte[] BinarySerialize(Object obj)
        {
            byte[] serializedObject;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter b = new BinaryFormatter();
            try
            {
                b.Serialize(ms, obj);
                ms.Seek(0, 0);
                serializedObject = ms.ToArray();
                ms.Close();
                return serializedObject;
            }
            catch
            {
                throw new SerializationException("Failed to serialize. Reason: ");
            }

        }