English 中文(简体)
C# - Deserialize a list<String>
原标题:C# - Deserialize a List<String>

我可以把名单编成一个非常容易的清单:

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读物并装上它?


EDIT:SerialzeObject没有建筑。 我早些时候在我的项目中做了发言,并对此表示.。 当我发现时,我认为这是在建的。 如果你是好奇的话,我就这样说:

// 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();
}
最佳回答

不存在诸如航天等建筑方法。 目的,但很难说出。

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);
  }
}
问题回答

这些是我的序列/代号推广方法,非常有用

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,自创建序列器以来,它就走到了那里,如果你在座标上使用同一物,就会加快你的 app。

我不敢肯定这是否会帮助你,但我已经讨论了我认为与你相似的东西。

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

这使我能够把我的所有数据重新编成一个清单和提纲;而且,我建议把它放在一个尝试中——安全套中。 事实上,现在只是看一下,我会把这变成一个“使用”的集团。

我希望这一帮助。

http://www.un.org。

道歉,只是注意到你试图以不同的方式来做,但我却不去回答。

我在放弃反对时正出现错误。 错误为。 XML文件(0,0)“有错误。 我修改了最初由“JaredPar”写成的“星号”功能,以解决这一错误。 对某人可能有用:

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

编制产品清单

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签