简体   繁体   English

不定义类型的XML序列化

[英]XML serialization without defining types

Is there any way to build a generic method for XML serialization and deserialization that doesn't require a bunch of gymnastics including pre-defining types using something like XmlInclude? 有没有什么方法可以构建用于XML序列化和反序列化的通用方法,而无需使用诸如XmlInclude之类的预定义类型的大量技巧? The code that I need to build cannot rely on pre-defined types. 我需要构建的代码不能依赖于预定义的类型。 I'm assuming Reflection could be used here, but I can't find an adequate solution. 我假设可以在这里使用反射,但是找不到合适的解决方案。 The ones I've tried from NuGet each have limitations: 我从NuGet尝试过的每个都有局限性:

  • Polenter seems to produce unusable output that cannot be deserialized Polenter似乎产生了无法反序列化的无法使用的输出
  • Global, Netfx requires type definitions ahead of time 全局,Netfx要求提前定义类型
  • Bender is beautiful but doesn't seem to support objects embedded within the object being serialized Bender很漂亮,但似乎不支持嵌入在要序列化的对象中的对象
  • XSerializer and JsonFX are what I need on the serialization side but the output won't deserialize XSerializer和JsonFX是我在序列化方面需要的,但是输出不会反序列化

The standard XmlSerializer won't work for obvious reasons (pre-defined types, XmlInclude, etc). 由于明显的原因(预定义的类型,XmlInclude等),标准XmlSerializer不能使用。

A simple example of what I need to serialize and then deserialize: 我需要序列化然后反序列化的简单示例:

    public class c1
    {
        public string name { get; set; }
        public object obj { get; set; }
    }

    public class c2
    {
        public string city { get; set; }
    }

    public static void Main(string[] args)
    {
        c1 class_1 = new c1();
        c2 class_2 = new c2();
        class_1.name = "david";
        class_2.city = "chicago";
        class_1.obj = class_2;

        string xml = <insert here>;
        Console.WriteLine("XML: " + xml);

        c1 deserialized = new c1();
        deserialized = <insert here>;
        Console.WriteLine("City: " + ((c2)c1.obj).city);
    }

Does something like this even exist? 这样的东西是否存在?

I'm not sure what you mean by "not defining types". 我不确定“未定义类型”是什么意思。 If it's an object your code is working with, it has a type. 如果它是您的代码正在使用的对象,则它具有类型。 The easiest thing to do would be to write your code to work against ISerializable - then it can work with any serializable type - even those that your code isn't aware of at build time. 最简单的方法是编写代码以使其与ISerializable兼容-然后它可以与任何可序列化的类型一起使用-甚至那些在构建时代码不知道的类型。 Alternatively, if you are working with dynamic objects (object's whose members are defined at runtime) check out this question for an example of making an ISerializable DynamicObject: https://stackoverflow.com/a/7501960/518955 另外,如果您正在使用动态对象(在运行时定义其成员的对象),请查看此问题,以获取制作ISerializable动态对象的示例: https ://stackoverflow.com/a/7501960/518955

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM