You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从XML文件反序列化生成List<Car>对象

没问题,我来帮你搞定这两个需求:从XML文件还原出List<Car>对象,再把数据绑定到ListView上。

1. 从XML反序列化创建List对象

你已经用DataContractSerializer完成了序列化,反序列化的逻辑和它完全对称,只需要打开文件流后调用ReadObject方法就行。另外要注意Car类的DataContract命名空间必须和XML里的一致,不然会解析失败。

首先确保你的Car类定义正确(带命名空间):

using System.Runtime.Serialization;

[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/DataSerialize")]
public class Car
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Make { get; set; }
    [DataMember]
    public string Model { get; set; }
    [DataMember]
    public int Year { get; set; }
}

反序列化的代码:

private async Task<List<Car>> LoadCarsFromXmlAsync()
{
    const string XMLFILENAME = "你的文件名.xml"; // 替换成你实际的文件名
    var serializer = new DataContractSerializer(typeof(List<Car>));
    
    try
    {
        using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(XMLFILENAME))
        {
            return (List<Car>)serializer.ReadObject(stream);
        }
    }
    catch (FileNotFoundException)
    {
        // 如果文件不存在,返回空列表或者初始化默认数据
        return new List<Car>();
    }
}
2. 将List绑定到ListView

绑定的方式分两种,简单的后台直接赋值适合小场景,MVVM模式更适合复杂项目,这里两种都给你参考:

方式一:后台代码直接赋值(简单场景)

先在XAML里定义ListView的展示结构:

<ListView x:Name="CarsListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="10">
                <TextBlock Text="{Binding Id}" FontWeight="Bold" FontSize="16"/>
                <TextBlock Text="{Binding Make}"/>
                <TextBlock Text="{Binding Model}"/>
                <TextBlock Text="{Binding Year}"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

然后在页面的加载事件里调用反序列化方法并赋值:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    var cars = await LoadCarsFromXmlAsync();
    CarsListView.ItemsSource = cars;
}

方式二:MVVM模式(适合复杂项目)

  1. 创建ViewModel类,实现INotifyPropertyChanged(确保数据更新时UI自动同步):
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class CarsViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Car> _cars;
    public ObservableCollection<Car> Cars
    {
        get => _cars;
        set
        {
            _cars = value;
            OnPropertyChanged();
        }
    }

    public async Task LoadCarsAsync()
    {
        var carsList = await LoadCarsFromXmlAsync(); // 复用之前的反序列化方法
        Cars = new ObservableCollection<Car>(carsList);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  1. 在XAML里设置页面的DataContext,并绑定ListView:
<Page.DataContext>
    <local:CarsViewModel x:Name="ViewModel"/>
</Page.DataContext>

<ListView ItemsSource="{Binding Cars}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="10">
                <TextBlock Text="{Binding Id}" FontWeight="Bold" FontSize="16"/>
                <TextBlock Text="{Binding Make}"/>
                <TextBlock Text="{Binding Model}"/>
                <TextBlock Text="{Binding Year}"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
  1. 在页面加载时触发数据加载:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    await ViewModel.LoadCarsAsync();
}

这样就能完美实现从XML读取数据,再绑定到ListView展示的需求啦!

内容的提问来源于stack exchange,提问作者user7342089

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:36:10