且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

哈希表转换为XML字符串,返回哈希表,而不使用.NET串行

更新时间:2022-11-14 09:01:41

您可以使用的DataContractSerializer 类:

using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

public class MyClass
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

class Program
{
    static void Main()
    {
        var table = new Hashtable
        {
            { "obj1", new MyClass { Foo = "foo", Bar = "bar" } },
            { "obj2", new MyClass { Foo = "baz" } },
        };

        var sb = new StringBuilder();
        var serializer = new DataContractSerializer(typeof(Hashtable), new[] { typeof(MyClass) });
        using (var writer = new StringWriter(sb))
        using (var xmlWriter = XmlWriter.Create(writer))
        {
            serializer.WriteObject(xmlWriter, table);
        }

        Console.WriteLine(sb);

        using (var reader = new StringReader(sb.ToString()))
        using (var xmlReader = XmlReader.Create(reader))
        {
            table = (Hashtable)serializer.ReadObject(xmlReader);
        }
    }
}