解析MapQuest XML响应

时间:2014-06-14 04:59:37

标签: c# xml

这是返回的xml:

<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>

我想将其提取为两个简短的描述符,从shortDesc和severity获得。到目前为止,这是我的C#尝试:

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];
}

基本上我想将事件的描述存储在严重性数组中的incidentsDscrp数组和严重性级别,然后将它们作为文本添加到winforms标签中。

编辑:我的错误是索引在

的数组范围之外
severity[count] = incidents.Element("severity").value;

线

2 个答案:

答案 0 :(得分:1)

使用以下内容来解析并创建标签 -

 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);

答案 1 :(得分:1)

很抱歉,但是你做错了。

首先,存储这样的数据(在并行集合中)是一个非常糟糕的主意。您应该阅读Jon Skeet的以下博文:Anti-pattern: parallel collections

现在,解决您的问题。这是一个简单的LINQ to XML查询,它允许您从XML文档中获得所需的一切:

var items = from i in xDoc.Root.Element("Incidents").Elements("Incident")
            select new
            {
                ShortDescription = (string)i.Element("shortDesc"),
                Severity = (int)i.Element("severity")
            };

您可以使用String.Join

将所有项目加入字符串
var text = String.Join(",", items.Select(x => string.Format("{0}: {1}", x.ShortDescription.Trim(), x.Severity.ToString())));

对于您的示例文档,text的值为:

  

I-65:退出59 TN-840和65号出口TN-96:3之间的维护工作

更改格式字符串的分隔符以获得所需的结果。现在您可以将其分配给标签:

trafficLabel.Text = text;