【问题标题】:Convert Hashtable to xml string and back to HashTable without using .NET Serializer不使用 .NET Serializer 将 Hashtable 转换为 xml 字符串并返回 HashTable
【发布时间】:2011-09-06 08:43:06
【问题描述】:

有谁知道如何在不使用基于 .NET 的 XMLSerializer 的情况下将 Hashtable 转换为 XML 字符串,然后再转换回 HashTable。当代码在 IE 中运行并且浏览器的保护模式打开时,XMLSerializer 会带来一些安全问题 -

所以基本上我正在寻找一种简单的方法将该哈希表转换为字符串并返回哈希表。

任何示例代码将不胜感激。

谢谢

【问题讨论】:

    标签: c# hashtable


    【解决方案1】:

    我没有时间测试这个,但是试试:

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

    【讨论】:

    • 找不到源类型“System.Collections.Hashtable”的查询模式的实现
    • 它不起作用,因为 hastable 没有实现 ienumerator 来针对它执行 LINQ
    【解决方案2】:

    您可以使用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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 2011-09-21
      • 2019-11-03
      相关资源
      最近更新 更多