C# Reading multiple parts of XML

I’m building a Windows app using a XML file with a lot of nesting in it – like this.

I need to access an attribute as I go down the nodes. I need to keep doing this for every “route” object available (Which may have multiple destinations and trips).

So my end Trip Object will have:

RouteNo = O
Destination = Queenspark
ETA = 28

The XML file:

<JPRoutePositionET xsi:schemaLocation="urn:connexionz-co-nz:jp JourneyPlanner.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:connexionz-co-nz:jp">
    <Content MaxArrivalScope="60" Expires="2015-06-14T20:21:01+12:00"/>
    <Platform Name="Manchester St & Gloucester St" PlatformTag="3330">
        <Route Name="Orange Line" RouteNo="O">
            <Destination Name="Queenspark">
                <Trip WheelchairAccess="true" TripNo="5497" ETA="28"/>
                <Trip WheelchairAccess="true" TripNo="5498" ETA="59"/>
            </Destination>
        </Route>
    </Platform>
</JPRoutePositionET>

My C# Code:

{   
    XDocument loadedData = XDocument.Load(streamReader);
    string StopName = loadedData.Root.Element("Platform").Attribute("Name").Value.ToString();

    var data = from query in loadedData.Descendants("Route")
               select new Trip
               {
                   RouteNo = (string)query.Attribute("RouteNo").Value ?? "test",
                   Destination = (string)query.Descendants("Destination").First().Attribute("Name").Value ?? "test",
                   Eta = (string)query.Element("Trip").Attribute("ETA").Value ?? "5"
               };

    List<Trip> trip = new List<Trip>();
    foreach(var a in data)
    {
        trip.Add(a);
    }

    var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
    try
    {
        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
             listView.ItemsSource = data.ToList();
        });

    }
    catch
    {

    }
}

Right now, my code just runs and doesn’t display anything. The debugger also shows nothing parsed from the XML. I think I’ve got my Descendents / Elements mixed up, I’d appreciate your help!


Source: xml

Leave a Reply