C# - 反序列化列表

发布于 2024-08-20 11:00:12 字数 855 浏览 7 评论 0原文

我可以非常容易地序列化列表:

List<String> fieldsToNotCopy =new List<String> {"Iteration Path","Iteration ID"};
fieldsToNotCopy.SerializeObject("FieldsToNotMove.xml");

现在我需要一个这样的方法:

List<String> loadedList = new List<String();
loadedList.DeserializeObject("FieldsToNotMove.xml");

有这样的方法吗?或者我是否需要创建一个 XML 读取器并以这种方式加载它?


编辑:事实证明没有内置 SerialzeObject。我在项目的早期做过一个,后来忘记了。当我发现它时,我以为它是内置的。如果您好奇,这是我制作的 SerializeObject:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
   XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
   TextWriter textWriter = new StreamWriter(filename);

   xmlSerializer.Serialize(textWriter, toSerialize);
   textWriter.Close();
}

I can serialize a list really easy:

List<String> fieldsToNotCopy =new List<String> {"Iteration Path","Iteration ID"};
fieldsToNotCopy.SerializeObject("FieldsToNotMove.xml");

Now I need a method like this:

List<String> loadedList = new List<String();
loadedList.DeserializeObject("FieldsToNotMove.xml");

Is there such a method? Or am I going to need to create an XML reader and load it in that way?


EDIT: Turns out there is no built in SerialzeObject. I had made one earlier in my project and forgot about it. When I found it I thought it was built in. In case you are curious this is the SerializeObject that I made:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
   XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
   TextWriter textWriter = new StreamWriter(filename);

   xmlSerializer.Serialize(textWriter, toSerialize);
   textWriter.Close();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

你对谁都笑 2024-08-27 11:00:12

没有像 SerializeObject 这样的内置方法,但编写一个方法并不是非常困难。

public void SerializeObject(this List<string> list, string fileName) {
  var serializer = new XmlSerializer(typeof(List<string>));
  using ( var stream = File.OpenWrite(fileName)) {
    serializer.Serialize(stream, list);
  }
}

并反序列化

public void Deserialize(this List<string> list, string fileName) {
  var serializer = new XmlSerializer(typeof(List<string>));
  using ( var stream = File.OpenRead(fileName) ){
    var other = (List<string>)(serializer.Deserialize(stream));
    list.Clear();
    list.AddRange(other);
  }
}

There is no such builtin method as SerializeObject but it's not terribly difficult to code one up.

public void SerializeObject(this List<string> list, string fileName) {
  var serializer = new XmlSerializer(typeof(List<string>));
  using ( var stream = File.OpenWrite(fileName)) {
    serializer.Serialize(stream, list);
  }
}

And Deserialize

public void Deserialize(this List<string> list, string fileName) {
  var serializer = new XmlSerializer(typeof(List<string>));
  using ( var stream = File.OpenRead(fileName) ){
    var other = (List<string>)(serializer.Deserialize(stream));
    list.Clear();
    list.AddRange(other);
  }
}
影子的影子 2024-08-27 11:00:12

这些是我的序列化/反序列化扩展方法,工作得很好

public static class SerializationExtensions
{
    public static XElement Serialize(this object source)
    {
        try
        {
            var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
            var xdoc = new XDocument();
            using (var writer = xdoc.CreateWriter())
            {
                serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
            }

            return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
        }
        catch (Exception x)
        {
            return new XElement("Error", x.ToString());
        }
    }

    public static T Deserialize<T>(this XElement source) where T : class
    {
        try
        {
            var serializer = XmlSerializerFactory.GetSerializerFor(typeof(T));

            return (T)serializer.Deserialize(source.CreateReader());
        }
        catch //(Exception x)
        {
            return null;
        }
    }
}

public static class XmlSerializerFactory
{
    private static Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();

    public static XmlSerializer GetSerializerFor(Type typeOfT)
    {
        if (!serializers.ContainsKey(typeOfT))
        {
            System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

            var newSerializer = new XmlSerializer(typeOfT);
            serializers.Add(typeOfT, newSerializer);
        }

        return serializers[typeOfT];
    }
}

你只需要为你的列表定义一个类型并使用它哦

public class StringList : List<String> { }

,你不需要 XmlSerializerFactory,它就在那里,因为创建序列化器很慢,如果你一遍又一遍地使用同一个,这可以加快您的应用程序的速度。

These are my serialize/deserialize extension methods that work quite well

public static class SerializationExtensions
{
    public static XElement Serialize(this object source)
    {
        try
        {
            var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
            var xdoc = new XDocument();
            using (var writer = xdoc.CreateWriter())
            {
                serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
            }

            return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
        }
        catch (Exception x)
        {
            return new XElement("Error", x.ToString());
        }
    }

    public static T Deserialize<T>(this XElement source) where T : class
    {
        try
        {
            var serializer = XmlSerializerFactory.GetSerializerFor(typeof(T));

            return (T)serializer.Deserialize(source.CreateReader());
        }
        catch //(Exception x)
        {
            return null;
        }
    }
}

public static class XmlSerializerFactory
{
    private static Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();

    public static XmlSerializer GetSerializerFor(Type typeOfT)
    {
        if (!serializers.ContainsKey(typeOfT))
        {
            System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

            var newSerializer = new XmlSerializer(typeOfT);
            serializers.Add(typeOfT, newSerializer);
        }

        return serializers[typeOfT];
    }
}

You just need to define a type for your list and use it instead

public class StringList : List<String> { }

Oh, and you don't NEED the XmlSerializerFactory, it's just there since creating a serializer is slow, and if you use the same one over and over this speeds up your app.

守护在此方 2024-08-27 11:00:12

我不确定这是否会对你有帮助,但我有一些我认为与你相似的东西。

//A list that holds my data
private List<Location> locationCollection = new List<Location>();


public bool Load()
{
            //For debug purposes
            Console.WriteLine("Loading Data");

            XmlSerializer serializer = new XmlSerializer(typeof(List<Location>));
            FileStream fs = new FileStream("CurrencyData.xml", FileMode.Open);

            locationCollection = (List<Location>)serializer.Deserialize(fs);

            fs.Close();

            Console.WriteLine("Data Loaded");
            return true;
}

这允许我将所有数据反序列化回 List<> 中。但为了安全起见,我建议将其放在 try-catch 块中。事实上,现在只要看看这个就会让我在“使用”块中重写它。

我希望这有帮助。

编辑:

抱歉,刚刚注意到您正在尝试以不同的方式进行操作,但无论如何我都会将答案留在那里。

I'm not sure whether this will help you but I have dome something which I believe to be similar to you.

//A list that holds my data
private List<Location> locationCollection = new List<Location>();


public bool Load()
{
            //For debug purposes
            Console.WriteLine("Loading Data");

            XmlSerializer serializer = new XmlSerializer(typeof(List<Location>));
            FileStream fs = new FileStream("CurrencyData.xml", FileMode.Open);

            locationCollection = (List<Location>)serializer.Deserialize(fs);

            fs.Close();

            Console.WriteLine("Data Loaded");
            return true;
}

This allows me to deserialise all my data back into a List<> but i'd advise putting it in a try - catch block for safety. In fact just looking at this now is going to make me rewrite this in a "using" block too.

I hope this helps.

EDIT:

Apologies, just noticed you're trying to do it a different way but i'll leave my answer there anyway.

只想待在家 2024-08-27 11:00:12

我在反序列化对象时遇到错误。错误为“XML 文档 (0, 0) 中存在错误”。我修改了最初由 @JaredPar 编写的 Deserialize 函数来解决此错误。这可能对某人有用:

public static void Deserialize(this List<string> list, string fileName)
{
    XmlRootAttribute xmlRoot = new XmlRootAttribute();
    xmlRoot.ElementName = "YourRootElementName";
    xmlRoot.IsNullable = true;

    var serializer = new XmlSerializer(typeof(List<string>), xmlRoot);
    using (var stream = File.OpenRead(fileName))
    {
        var other = (List<string>)(serializer.Deserialize(stream));
        list.Clear();
        list.AddRange(other);
    }
}

I was getting error while deserializing to object. The error was "There is an error in XML document (0, 0)". I have modified the Deserialize function originally written by @JaredPar to resolve this error. It may be useful to someone:

public static void Deserialize(this List<string> list, string fileName)
{
    XmlRootAttribute xmlRoot = new XmlRootAttribute();
    xmlRoot.ElementName = "YourRootElementName";
    xmlRoot.IsNullable = true;

    var serializer = new XmlSerializer(typeof(List<string>), xmlRoot);
    using (var stream = File.OpenRead(fileName))
    {
        var other = (List<string>)(serializer.Deserialize(stream));
        list.Clear();
        list.AddRange(other);
    }
}
雨轻弹 2024-08-27 11:00:12

创建要序列化的产品列表 序列

List<string> Products = new List<string>
{
  new string("Product 1"),
  new string("Product 2"),
  new string("Product 3"),
  new string("Product 4")
};

using (FileStream fs = new FileStream(@"C:\products.txt", FileMode.Create))
{
   BinaryFormatter bf = new BinaryFormatter();
   bf.Serialize(fs, Products);
}

反序列化

using (FileStream fs = new FileStream(@"C:\products.txt", FileMode.Open))
{
    BinaryFormatter bf = new BinaryFormatter();
    var productList = (List<string>)bf.Deserialize(fs);
}

Create a list of products be serialized

List<string> Products = new List<string>
{
  new string("Product 1"),
  new string("Product 2"),
  new string("Product 3"),
  new string("Product 4")
};

Serialization

using (FileStream fs = new FileStream(@"C:\products.txt", FileMode.Create))
{
   BinaryFormatter bf = new BinaryFormatter();
   bf.Serialize(fs, Products);
}

Deserialization

using (FileStream fs = new FileStream(@"C:\products.txt", FileMode.Open))
{
    BinaryFormatter bf = new BinaryFormatter();
    var productList = (List<string>)bf.Deserialize(fs);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文