簡體   English   中英

將 Hashtable 轉換為 xml 字符串並返回 HashTable 而不使用 .NET 序列化程序

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

有誰知道如何在不使用基於 .NET 的 XMLSerializer 的情況下將哈希表轉換為 XML 字符串然后返回哈希表。 當代碼在 IE 中運行並且瀏覽器的保護模式打開時,XMLSerializer 會帶來一些安全問題 -

所以基本上我正在尋找一種簡單的方法來將該哈希表轉換為字符串並返回到哈希表。

任何示例代碼將不勝感激。

謝謝

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

我沒有時間對此進行測試,但請嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM