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

前端 未结 2 1055
死守一世寂寞
死守一世寂寞 2021-02-10 11:17

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

相关标签:
2条回答
  • 2021-02-10 11:47

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-10 11:53

    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)));
    
    0 讨论(0)
提交回复
热议问题