Reputation: 125
here is the xml returned :
<IncidentsResponse>
<Incidents>
<Incident>
<id>920959670</id>
<type>1</type>
<severity>3</severity>
<eventCode>701</eventCode>
<lat>35.91411</lat>
<lng>-86.82417</lng>
<startTime>2014-03-01T01:00:00.000-05:00</startTime>
<endTime>2016-06-16T00:59:00.000-04:00</endTime>
<shortDesc>
I-65 : Maintenance work between Exit 59 TN-840 and Exit 65 TN-96
</shortDesc>
<fullDesc>
Intermittent lane closures due to maintenance work on I-65 both ways between Exit 59 TN-840 and Exit 65 TN-96.
</fullDesc>
<delayFromTypical>0.0</delayFromTypical>
<delayFromFreeFlow>0.0</delayFromFreeFlow>
<distance>12.09</distance>
<iconURL>https://api.mqcdn.com/mqtraffic/const_mod.png</iconURL>
</Incident>
</Incidents>
</IncidentsResponse>
I want to extract this into two brief descriptors, obtained from shortDesc and severity. Here is my C# attempt so far :
string[] incidentsDscrp = { };
string[] severity = { };
int count = 0;
XDocument doc = XDocument.Parse(traffData);
foreach (var incidents in doc.Descendants("Incident"))
{
incidentsDscrp[count] = incidents.Element("shortDesc").Value;
severity[count] = incidents.Element("severity").Value;
count++;
}
trafficLabel.Text = "";
for (int a = 0; a < incidentsDscrp.Length; a++)
{
trafficLabel.Text += incidentsDscrp[a];
trafficLabel.Text += severity[a];
}
Basically I want to store descriptions of incidents in the incidentsDscrp array and severity level in the severity array, and then add them as text to a winforms label.
Edit : My error is that index was outside bounds of the array at the
severity[count] = incidents.Element("severity").value;
line
Upvotes: 0
Views: 105
Reputation: 125650
Sorry to say, but you're doing it wrong.
First of all, storing data like that (in parallel collections), is a really bad idea. You should read following blog post by Jon Skeet: Anti-pattern: parallel collections.
Now, to solve your problem. Here is a little LINQ to XML query which allows you to get all you need from XML document:
var items = from i in xDoc.Root.Element("Incidents").Elements("Incident")
select new
{
ShortDescription = (string)i.Element("shortDesc"),
Severity = (int)i.Element("severity")
};
You can join all the items into a string using String.Join
:
var text = String.Join(",", items.Select(x => string.Format("{0}: {1}", x.ShortDescription.Trim(), x.Severity.ToString())));
For your sample document, text
s value is:
I-65 : Maintenance work between Exit 59 TN-840 and Exit 65 TN-96: 3
Change separator of format string to get desired result. Now you can assign it to the label:
trafficLabel.Text = text;
Upvotes: 1
Reputation: 1474
Use following to parse and create a label -
from c in trafficData.Descendants("Incident")
select new
{
ShortDescription = c.Element("shortDesc").Value,
Severity = c.Element("severity").Value
}).Aggregate((a,b) => a.ShortDescription +": " + a.Severity +", "
+ b.ShortDescription +": " + b.Severity);
Upvotes: 1