开发者

(De)Serializing "Object"s

开发者 https://www.devze.com 2023-04-09 23:55 出处:网络
I have to XML (de)serialize the following class: this gives the following output: <ArrayOfPropertyFilter xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"

I have to XML (de)serialize the following class:

(De)Serializing "Object"s

this gives the following output:

<ArrayOfPropertyFilter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PropertyFilter>
    <AndOr>And</AndOr>
    <LeftBracket>None</LeftBracket>
    <Property>17</Property>
    <Operator>Equal</Operator>
    <Value xsi:type="xsd:string">lll</Value>
    <RightBracket>None</RightBracket>
  </PropertyFilter>
</ArrayOfPropertyFilter>

and, after deserialization it gives

(De)Serializing "Object"s

How can I "tell" to Serializer to keep the Value "as is", without any XML node....(in the concrete case the Value should be "lll" and not XMLNode containing Text "lll") ?

EDIT

Bellow is a full working sample in C#. The output is

Value is = 'System.Xml.XmlNode[]'

using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

namespace WindowsFormsApplication13
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PropertyFilter filter = new PropertyFilter();
            filter.AndOr = "Jora";
            filter.Value = "haha";
            filter.Property = 15;

            var xml = filter.SerializeToString();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);

            PropertyFilter cloneFilter = xmlDoc.Deserialize<PropertyFilter>();

            Console.WriteLine("Value is = '{0}'", cloneFilter.Value);
        }
    }

    public class PropertyFilter
    {
        public string AndOr { get; set; }
        public string LeftBracket { get; set; }
        public int Property { get; set; }
        public string Operator { get; set; }
        public object Value { get; set; }
        public string RightBracket { get; set; }
    }

    public static class Utils
    {
        public static string SerializeToString(this object instance)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlSerializer serializer = new XmlSerializer(
                instance.GetType(), null, new Type[0], null, null);
            serializer.Serialize(sw, instance);
            return sb.ToString();
        }

        public static T Deserialize<T>(this XmlDocument xmlDoc)
        {
            XmlNodeReader reader = new XmlNodeReader(xmlDoc.DocumentElement);
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            object obj = serializer.Deserialize(reader);
            T myT = (T)obj;
            return myT;
        }

    }
}

EDIT 2

To stress the Anton answer, the second example (updated with the Groo's remarks):

using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

namespace WindowsFormsApplication13
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PropertyFilter filter = new PropertyFilter();
            filter.AndOr = "Jora";
            var obj = new Hehe();
            obj.Behehe = 4526;
            filter.Value = obj;
            filter.Property = 15;

            var xml = filter.SerializeToString();
            PropertyFilter cloneFilter = xml.Deserialize<PropertyFilter>();

            Console.WriteLine("Value is = '{0}'", cloneFilter.Value);
        }
    }

    public class Hehe
    {
        public int Behehe { get; set; }
        public override string ToString()
     开发者_StackOverflow   {
            return string.Format("behehe is '{0}'", Behehe);
        }
    }

    public class PropertyFilter
    {
        public string AndOr { get; set; }
        public string LeftBracket { get; set; }
        public int Property { get; set; }
        public string Operator { get; set; }
        //[XmlElement(typeof(Hehe))]
        public object Value { get; set; }
        public string RightBracket { get; set; }
    }

    public static class Utils
    {
        public static string SerializeToString(this object instance)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");
            StringBuilder sb = new StringBuilder();

            XmlSerializer serializer = new XmlSerializer(instance.GetType(), null, new Type[0], null, null);
            using (StringWriter sw = new StringWriter(sb))
            {
                serializer.Serialize(sw, instance);
            }
            return sb.ToString();
        }

        public static T Deserialize<T>(this string xmlString)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringReader sr = new StringReader(xmlString))
            {
                return (T)serializer.Deserialize(sr);
            }
        }

    }
}


Ok, that makes sense, you were using a XmlDocument for deserialization. Simply use a String (or any stream reader, like @Seb already pointed out), and it will work:

public static class Utils
{
    public static string SerializeToString(this object instance)
    {
        if (instance == null)
            throw new ArgumentNullException("instance");

        StringBuilder sb = new StringBuilder();
        XmlSerializer serializer = new XmlSerializer(instance.GetType());

        using (StringWriter sw = new StringWriter(sb))
        {
            serializer.Serialize(sw, instance);
        }

        return sb.ToString();
    }

    public static T Deserialize<T>(this string xmlString)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (StringReader sr = new StringReader(xmlString))
        {
            return (T)serializer.Deserialize(sr);
        }
    }
}

Usage:

// serialize
var xml = filter.SerializeToString();

// deserialize
var cloneFilter = xml.Deserialize<PropertyFilter>();

[Edit]

Also, as a side note: never forget to dispose objects implementing IDisposable. That's why the using constructs are added for any instantiated Stream.

[Edit2]

As Anton said, in this case you need to specify extra types explicitly, because XmlSerializer doesn't search for all possible types to find a matching class.

A slightly better solution might be to use a XmlSerializer overload which accepts these types (so that you don't need to manually add attributes):

public static T Deserialize<T>(this string xmlString)
{
    Type[] typesToInclude = GetAllPossibleTypes();

    XmlSerializer serializer = new XmlSerializer(typeof(T), typesToInclude);
    using (StringReader sr = new StringReader(xmlString))
    {
        return (T)serializer.Deserialize(sr);
    }
}

This can be done once, at application startup, but you do need to provide the appropriate assembly (or several assemblies) to make sure that all possible types are covered:

public static class Utils
{
    private static readonly Type[] _typesToInclude = GetPossibleUserTypes();

    private static Type[] GetPossibleUserTypes()
    {
        // this part should be changed to load types from the assembly
        // that contains your potential Value candidates
        Assembly assembly = Assembly.GetAssembly(typeof(PropertyFilter));

        // get public classes only
        return assembly.GetTypes().Where(t => t.IsPublic && !t.IsAbstract).ToArray();
    }

    public static string SerializeToString(this object instance)
    {
        if (instance == null)
            throw new ArgumentNullException("instance");

        var sb = new StringBuilder();
        var serializer = new XmlSerializer(instance.GetType(), _typesToInclude);

        using (StringWriter sw = new StringWriter(sb))
        {
            serializer.Serialize(sw, instance);
        }

        return sb.ToString();
    }

    public static T Deserialize<T>(this string xmlString)
    {
        var serializer = new XmlSerializer(typeof(T), _typesToInclude);
        using (StringReader sr = new StringReader(xmlString))
        {
            return (T)serializer.Deserialize(sr);
        }
    }
}


Gree's solution will work as long as Value takes values of primitive, XSD-defined types like string and int, or user-defined types mentioned somewhere in T's definition (T itself, the types of its properties etc.) As soon as you need to deserialize a value of a type different from these, you must declare all possible types of Value with XmlElementAttribute, e.g.

[XmlElement (typeof (string))]
[XmlElement (typeof (int))]
[XmlElement (typeof (MyType), Namespace = "http://example.com/schemas/my")]
public object Value { get ; set ; }


Ok, try this but I'm not sure of what you're trying to achieve.

public class PropertyFilter
{
    public string AndOr {get; set;}
    public string LeftBracket {get; set;}
    public int Property {get; set;}
    public string Operator {get; set;}
    public object Value {get; set;}
    public string RightBracket {get; set;}
}
    public void MyMethod()
    {
        using (System.IO.StreamReader reader = new System.IO.StreamReader(@"Input.xml"))
        {
            System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(PropertyFilter[]));
            PropertyFilter[] deserialized = (PropertyFilter[])serializer.Deserialize(reader);
        }
    }

I just put your sample XML in Input.xml file. I hope this will help.

0

精彩评论

暂无评论...
验证码 换一张
取 消