列表按以下代码序列化:
var serializer = new DataContractSerializer(typeof(List<Car>));
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(XMLFILENAME, CreationCollisionOption.ReplaceExisting))
{
serializer.WriteObject(stream, Cars);
}
XML文件如下所示:
<ArrayOfCar xmlns="http://schemas.datacontract.org/2004/07/DataSerialize" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Car><Id>1</Id><Make>Oldsmobile</Make><Model>Cutlas Supreme</Model><Year>1985</Year></Car>
我不仅需要将此数据绑定到ListView,还需要根据该文件创建一个对象(List<Car>
)。
答案 0 :(得分:1)
大概重新打开文件,然后:
var cars = (List<Car>)serializer.ReadObject(stream);
然后将您的用户界面绑定到cars
。
答案 1 :(得分:0)
使用xml Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
new Car(FILENAME);
}
}
public class Car
{
public static List<Car> cars = null;
public int id { get; set;}
public string make { get; set;}
public string model { get; set;}
public int year { get; set;}
public Car() { }
public Car(string filename)
{
XDocument doc = XDocument.Load(filename);
cars = doc.Descendants().Where(x => x.Name.LocalName == "Car").Select(x => new Car()
{
id = x.Elements().Where(y => y.Name.LocalName == "Id").Select(y => (int)y).FirstOrDefault(),
make = x.Elements().Where(y => y.Name.LocalName == "Make").Select(y => (string)y).FirstOrDefault(),
model = x.Elements().Where(y => y.Name.LocalName == "Model").Select(y => (string)y).FirstOrDefault(),
year = x.Elements().Where(y => y.Name.LocalName == "Year").Select(y => (int)y).FirstOrDefault(),
}).ToList();
}
}
}