将XML解析为ListView Windows Metro

时间:2015-01-13 15:52:40

标签: xml xaml silverlight windows-phone-7 windows-phone-8

我正在为Windows 8.1开发一个应用程序。我能够将XML文件解析为ListView。它是本地XML文件,但是当我将XML路径(XMLFile1.xml)作为URL(例如http://192.168.x.x/test.xml)时,它会给我一个错误。 这是我的代码。

XAML文件:

<ListView x:Name="listView1" HorizontalAlignment="Left" Height="373" Margin="1229,264,0,0" VerticalAlignment="Top" Width="127">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="10" >
                        <TextBlock Text="{Binding FirstName}"/>
                        <TextBlock Text="{Binding LastName}"/>
                        <TextBlock Text="{Binding Age}"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

XAML.cs文件:

public class Person
        {
            string firstname;
            string lastname;
            int age;

            public string FirstName
            {
                get { return firstname; }
                set { firstname = value; }
            }

            public string LastName
            {
                get { return lastname; }
                set { lastname = value; }
            }

            public int Age
            {
                get { return age; }
                set { age = value; }
            }
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            string peopleXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "XMLFile1.xml");
            XDocument loadedData = XDocument.Load(peopleXMLPath);

            var data = from query in loadedData.Descendants("person")
                       select new Person
                       {
                           FirstName = (string)query.Element("firstname"),
                           LastName = (string)query.Element("lastname"),
                           Age = (int)query.Element("age")
                       };
            listView1.ItemsSource = data;
}

1 个答案:

答案 0 :(得分:1)

您需要列出尝试通过外部源加载数据时使用的代码。如果您尚未更改此设置,请尝试以下选项。

尝试更改

XDocument loadedData = XDocument.Load(peopleXMLPath);

XDocument loadedData = XDocument.Load("http://192.168.x.x/test.xml");