选择XML元素和属性

时间:2012-05-10 18:18:03

标签: c# xml linq api

我正在为WP7制作一个公式1应用程序。我使用API​​来检索信息。我设法检索驱动程序元素的属性,但我无法检索其下的元素。我使用了这个API:http://ergast.com/api/f1/2012/drivers

C#

namespace Formule1
{
public partial class DriversPage : PhoneApplicationPage
{
    const string URL = "http://ergast.com/api/f1/2012/";

    public DriversPage()
    {
        InitializeComponent();
        GetDrivers();
    }

    private void GetDrivers()
    {
        string resource = "drivers";           
        WebClient webclient = new WebClient();    
        webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted);           
        webclient.DownloadStringAsync(new Uri(URL + resource));
    }

    private void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            return;
        }
        // xml-resultaat parsen
        XDocument xmlEntries = XDocument.Parse(e.Result);
        // drivers eruit halen          

        List<Driver> drivers = new List<Driver>();

        var ns = xmlEntries.Root.Name.Namespace;
        drivers = (from element in xmlEntries.Root.Element(ns + "DriverTable").Descendants(ns + "Driver")
                   select new Driver(element.Attribute("driverId").Value, element.Element("GivenName").Value)).ToList<Driver>();


            DriverListBox.ItemsSource = drivers;

    }
}
}

API

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="http://ergast.com/schemas/mrd-1.2.xsl"?>
<MRData xmlns="http://ergast.com/mrd/1.2" series="f1"     url="http://ergast.com/api/f1/2012/drivers" limit="30" offset="0" total="24">
<DriverTable season="2012">
    <Driver driverId="alonso" url="http://en.wikipedia.org/wiki/Fernando_Alonso">
        <GivenName>Fernando</GivenName>
        <FamilyName>Alonso</FamilyName>
        <DateOfBirth>1981-07-29</DateOfBirth>
        <Nationality>Spanish</Nationality>
    </Driver>
     </DriverTable>
</MRData>

1 个答案:

答案 0 :(得分:2)

您的问题是必须使用正确的命名空间限定元素名称。将.Element("GivenName")更改为.Element(ns + "GivenName")