0

我正在尝试制作一个显示公交时间的应用程序,包括公交号码、目标时间和预期时间。

我从HttpWebRequest. 我对请求的响应存储在 XML 格式的字符串变量中。

我可以得到我想要的所有信息;比如公交时间、目标时间和预期时间。

问题是,如果没有预期时间,则不会显示任何内容。我喜欢在没有预期时间的情况下,我的代码只采用与目标时间相同的值:

一个例子

Bus | Aimed | Execepted
-----------------------
1   | 17:05 | 17:07
2   | 17:05 | <nothing> so take value of aimed -> 17:05

我已经有以下代码

//XMLResponse put in documentRoot
//responseFromServer is a string variable in XML format with all the information
XElement documentRoot = XDocument.Parse(responseFromServer).Root;
XNamespace ns = "http://www.siri.org.uk/";

var buses = (from tblBuses in documentRoot.Descendants(ns + "PublishedLineName")
             select tblBuses.Value).ToList();
var expHours = (from tblHours in documentRoot.Descendants(ns + "ExpectedDepartureTime")
               select tblHours.Value).ToList();

foreach (var bus in buses)
{
    string output = bus.Substring(bus.IndexOf('T') + 1);
    int index = output.IndexOf(".");

    if (index > 0)
        output = output.Substring(0, index);

    listBox1.Items.Add("Bus: " + output);
}


//Show every ExpectedDepartureTime
//If there is no expectedTime take value AimedDepartureTime
foreach (var expH in expHours)
{
    string output = expH.Substring(expH.IndexOf('T') + 1);
    int index = output.IndexOf(".");

    if (index > 0)
        output = output.Substring(0, index);

    lstHours.Items.Add(output);
}

为了更清楚地了解我的 XML 响应,下面是我的 XML 响应示例(一个带有 AimedDeparturetime 和 Expected,一个没有 Expected)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Siri version="1.0" xmlns="http://www.siri.org.uk/">
<ServiceDelivery>
<ResponseTimestamp>2013-03-26T16:09:48.181Z</ResponseTimestamp>
<StopMonitoringDelivery version="1.0">
<ResponseTimestamp>2013-03-26T16:09:48.181Z</ResponseTimestamp>
<RequestMessageRef>12345</RequestMessageRef>

<MonitoredStopVisit>
<RecordedAtTime>2013-03-26T16:09:48.181Z</RecordedAtTime>
<MonitoringRef>020035811</MonitoringRef>
<MonitoredVehicleJourney>
<FramedVehicleJourneyRef>
<DataFrameRef>-</DataFrameRef>
<DatedVehicleJourneyRef>-</DatedVehicleJourneyRef>
</FramedVehicleJourneyRef>
<VehicleMode>bus</VehicleMode>
<PublishedLineName>2</PublishedLineName>
<DirectionName>Elstow P+R</DirectionName>
<OperatorRef>STB</OperatorRef>
<MonitoredCall>
<AimedDepartureTime>2013-03-26T16:11:00.000Z</AimedDepartureTime>
<ExpectedDepartureTime>2013-03-26T16:11:28.000Z</ExpectedDepartureTime>
</MonitoredCall>
</MonitoredVehicleJourney>
</MonitoredStopVisit>
---------------------------------------------------

<MonitoredStopVisit>
<RecordedAtTime>2013-03-26T16:09:48.181Z</RecordedAtTime>
<MonitoringRef>020035811</MonitoringRef>
<MonitoredVehicleJourney>
<FramedVehicleJourneyRef>
<DataFrameRef>-</DataFrameRef>
<DatedVehicleJourneyRef>-</DatedVehicleJourneyRef>
</FramedVehicleJourneyRef>
<VehicleMode>bus</VehicleMode>
<PublishedLineName>53</PublishedLineName>
<DirectionName>Wootton</DirectionName>
<OperatorRef>STB</OperatorRef>
<MonitoredCall>
<AimedDepartureTime>2013-03-26T16:19:00.000Z</AimedDepartureTime>
</MonitoredCall>
</MonitoredVehicleJourney>
</MonitoredStopVisit>
</StopMonitoringDelivery>
</ServiceDelivery>
</Siri>

所以此刻我的应用程序并没有显示公共汽车的每个出发时间。

我该如何解决这个问题?

谢谢!

4

2 回答 2

3

Apologies upfront, because this is not the greatest XML parsing ever, but I would adjust my LINQ query:

var buses = from tblBuses in documentRoot.Descendants(ns + "MonitoredVehicleJourney")
            select new
                   {
                       LineName = tblBuses.Descendants(ns + "PublishedLineName").Single().Value,
                       AimedHours = tblBuses.Descendants(ns + "AimedDepartureTime").Single().Value,
                       ExpectedHours = tblBuses.Descendants(ns + "ExpectedDepartureTime").Select(el => el.Value).SingleOrDefault()
                   };

This will create an IEnumerable of some anonymous type which allows you to access the bus data more easily in subsequent code:

foreach (var bus in buses)
{
    // Take ExpectedHours, or AimedHours if the first is null
    string expH = bus.ExpectedHours ?? bus.AimedHours

    // Same code as before here
    string output = expH.Substring(expH.IndexOf('T') + 1);
    int index = output.IndexOf(".");
    if (index > 0)
        output = output.Substring(0, index);
    lstHours.Items.Add(output);
}

In your original code, buses that did not have an <ExpectedDepartureTime> were never iterated over because they never show up in your expHours List. In contrast, this LINQ query will contain all buses. It assumes that they all have a single <AimedDepartureTime> and an optional <ExpectedDepartureTime>.

For the expected departure time, I used a Select to get the element value for each of the descendants. Using SingleOrDefault().Value cannot be used, because the query might yield no elements and get_Value() would be called on a null reference.

One last comment about my query: for production code I would refrain from using Descendants and do more strict querying of the XML structure.

于 2013-03-26T18:49:48.670 回答
2

您可以在一个 linq 查询中执行所有操作,并使用?:条件运算符选择正确的输出:

var buses = 
    (from tblBuses in documentRoot.Descendants(ns + "PublishedLineName")
     let bus = tblBuses.Value
     let output = bus.Substring(bus.IndexOf('T') + 1)
     let index = output.IndexOf(".")
     select (index > 0) ? output.Substring(0, index) : output);

foreach (var bus in buses)
{
    listBox1.Items.Add("Bus: " + bus);
}

甚至

var buses =
    (from ...
     select "Bus: " + ((index > 0) ? output.Substring(0, index) : output));
    .ToArray();

listBox1.Items.AddRange(buses);

相同的模式可以应用于expHours.

于 2013-03-26T17:10:59.227 回答