Convert Hashtable to xml string and back to HashTable without using .NET Serializer

喜你入骨 提交于 2019-12-04 14:14:28

问题


Does anyone know how to convert a Hashtable to an XML String then back to a HashTable without using the .NET based XMLSerializer. The XMLSerializer poses some security concerns when code runs inside of IE and the browser's protected mode is turned on -

So basically I am looking for an easy way to convert that Hashtable to string and back to a Hashtable.

Any sample code would be greatly appreciated.

Thanks


回答1:


You could use the DataContractSerializer class:

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



回答2:


I don't have time to test this, but try:

XDocument doc = new XDocument("HashTable",
                               from de in hashTable
                               select new XElement("Item",
                                                   new XAttribute("key", de.Key),
                                                   new XAttribute("value", de.Value)));


来源:https://stackoverflow.com/questions/6202780/convert-hashtable-to-xml-string-and-back-to-hashtable-without-using-net-seriali

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!